cllpse
cllpse

Reputation: 21727

FirstOrDefault() unable to couple with ?? operator

As far as I can understand, the linq method FirstOrDefault() returns null if a record-set is empty. Why can't use the ?? operator against the function? Like so:

Double d = new Double[]{}.FirstOrDefault() ?? 0.0;


Update

I don't want to check if d is null later on in my code. And doing:

Double d new Double[]{}.FirstOrDefault() == null
       ? 0.0 
       : new Double[]{}.FirstOrDefault();

... or:

var r = new Double[]{}.FirstOrDefault();

Double d = r == null ? 0.0 : r;

... seems a bit overkill--I'd like to do this null-check in one line of code.

Upvotes: 7

Views: 2844

Answers (5)

Ani
Ani

Reputation: 113442

Although others have answered why you have compilation problems here, you are right that this is problematic for value types. To my knowledge, there is no way of knowing in this case whether a result of zero was because the first item really was zero, or because the IEnumerable<double>was empty.

In the example you have given, the fallback value is zero anyway, so all you need is:

var r = new double[]{...}.FirstOrDefault();

Assuming you had a non-zero fallback value, you have a few options:

var r = !myDoubles.Any() ? fallback : myDoubles.First();

or

var r = myDoubles.Cast<double?>().FirstOrDefault() ?? fallback;

If you have Zen Linq Extensions, you can do:

var r = myDoubles.FirstOrFallback(fallback);

Upvotes: 0

Alex
Alex

Reputation: 35407

Making it nullable should work. But, then your making it nullable, all depends on your scenario...

Double d = new Double?[] { }.FirstOrDefault() ?? 0.0;

Upvotes: 1

Coding Flow
Coding Flow

Reputation: 21881

The method is called FirstOrDefault not FirstOrNull, i.e. it will return 0, the default value of a double anyway so there isn't a need for the ??.

Upvotes: 6

James Curran
James Curran

Reputation: 103535

Actually, FirstOrDefault<T>() returns T, which is either a value or default(T).

default(T) is either null or (T)0 for value types (like double)

Upvotes: 11

Darin Dimitrov
Darin Dimitrov

Reputation: 1039160

Because the null-coalescing operator (??) applies only to nullable reference types while Double is a value type. You could use a nullable double instead (double?).

Upvotes: 11

Related Questions