How can you check to see whether the object returned by the FirstOrDefault
LINQ function is in fact the default?
For example:
Contact conta
You wouldn't need to perform that equals check because your query only returns objects where the contantName is Stackoverflow
. When you use FirstOrDefault
it returns null
if no objects were found so you can do
if(contact == null)
do something
You know it's a reference type if Contact is a class so it's default value would be null. You can, however, check it's the default type of any object (reference or value) by using default
.
if(contact == default(Contact))
do something
As mentioned in the comments, you can possibly make your code more efficient by using the overload of FirstOrDefault
that takes a predicate.
FirstOrDefault(m => m.contactName == "Stackoverflow")
You can also change the default value returned if your program needs to work with something other than a null
or 0
. For example
Contact defaultContact = new Contact();
defaultContact.ContactName = "StackExchange";
Contact contact = dbo.contact.Where(m=>m.contactName == "Stackoverflow")
.DefaultIfEmpty(defaultContact).First();
The above will return the defaultContact
object if no other object was found (instead of returning null). If you do this then you don't need to check for null
or default(T)
because you know you have a Contact
object.
FirstOrDefault
will return null
for reference types and default
for value types. Thus your test is invalid. In orther to check wheteher the value is default, you should compare it with default (Type)
:
Contact contact = dbo.contact.FirstOrDefault(m => m.contactName == "Stackoverflow");
if (!object.Equals(contact, default (Contact)))
// Is not default
The code above will work with either struct Contact
or class Contact
. We also assume that default (Contact)
is never a valid return value of our query.