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”?
FirstOrDefaultwill 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 thedefaultvalue will be 0. So, checking ifnullwould not work.Consider:
Here
xwould equal0How about a reference type?
Here
xwould benullThis is probably the better of the two approaches: