When i am querying database with .FirstOrDefault
method, how do i handle results that it has given to me? I am especially concerned about null values, currently i have something like that:
if (result == default(TypeOfResult))
{
handleIt();
}
But i do not exactly know what is this "default", so i am wondering if it wasn't better to do it this way:
if (result == null)
{
handleIt();
}
which one would work? And what exactly is this "default"?
FirstOrDefault
will return the first element in the sequence or literally the default value for the type in question.
So depending on what you're querying the default value may change. For example, a collection of int
's the default
value will be 0. So, checking if null
would not work.
Consider:
List<int> s = new List<int>();
var x = s.FirstOrDefault();
Here x
would equal 0
How about a reference type?
List<MyCustomClass> s = new List<MyCustomClass>();
var x = s.FirstOrDefault();
Here x
would be null
This is probably the better of the two approaches:
if (result == default(TypeOfResult))
{
handleIt();
}
If TypeOfResult
is a reference type then
result == default(TypeOfResult)
and result == null
means the same thing.
Because the default value for reference types in null
.
The default keyword just returns a "default value" for a given type which in case of reference types in null
. For value types it depends on the type e.g. 0 for int
etc.
And as the name implies FirstOrDefault
will return the first element of the collection or the default value for the given type if the collection is empty.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With