Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i handle .FirstOrDefault method?

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"?

like image 234
ojek Avatar asked Dec 07 '22 12:12

ojek


2 Answers

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();
}
like image 67
Gabe Avatar answered Dec 23 '22 06:12

Gabe


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.

like image 25
nemesv Avatar answered Dec 23 '22 06:12

nemesv