Reputation: 10068
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"?
Upvotes: 4
Views: 1389
Reputation: 5322
If you want do ensure that your code can work failsave with default(T) where T is a value type you can box your items in the Nullable object.
For example:
var ints = new List<int>(){1,2,3,4,6};
int result = ints.Where(i => i == 0).FirstOrDefault();
result is 0 even if there is no 0 in the list!
var ints = new List<int>(){1,2,3,4,6};
var nullable = ints.Select(i => new Nullable<int>(i));
var result = nullable.Where(i => i == 0).FirstOrDefault()
result is null, there is no 0 in the list!
This is of course slower and requires more memory, but also works for non-value types.
Upvotes: 1
Reputation: 50493
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();
}
Upvotes: 8
Reputation: 2954
You should check with Null. FirstOrDefault will return NULL if cannot find any result.
See this POST
Upvotes: 0
Reputation: 139758
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.
Upvotes: 6