tags:

views:

313

answers:

2

Say I have following the following snippet (context narrowed down to limit scope of question)

int? nullableId = GetNonNullableInts().FirstOrDefault();

Because GetNonNullableInts() returns ints, the FirstOrDefault will default to 0.
Is there a way to make the FirstOrDefault on a list of ints return a null value when the list is empty?

+10  A: 
int? nullableId = GetNonNullableInts().Cast<int?>().FirstOrDefault();
Matt Howells
Is there no way to define the Default from FirstOrDefault?When the list does return a set of ints, casting them all for no real reason doesn't really look like a good idea to me.
borisCallens
Cast() does not cast them all - it only casts them as you enumerate. So this code will cast either zero or one ints - not much of a performance hit.
Matt Howells
You cannot define the default value returned by FirstOrDefault - it returns either the first element from the enumerable, or if none exists, the result of `default(T)`.
Matt Howells
You are correct, I was confused. Parsing one value is no biggy.
borisCallens
And if you want to implement FirstOrValue, here's an article on how to do it wrong vs how to do it right: http://stackoverflow.com/questions/1708846/a-different-take-on-firstordefault
Eric Lippert
A: 

FirstOrDefault depends on T from IEnumerable<T> to know what type to return, that's why you're receiving int instead int?.

So you'll need to cast your items to int? before return any value, just like Matt said

Rubens Farias