Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FirstOrDefault() unable to couple with ?? operator

Tags:

c#

linq

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.

like image 427
cllpse Avatar asked Aug 13 '10 11:08

cllpse


3 Answers

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)

like image 136
James Curran Avatar answered Nov 11 '22 22:11

James Curran


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?).

like image 43
Darin Dimitrov Avatar answered Nov 11 '22 23:11

Darin Dimitrov


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

like image 26
Ben Robinson Avatar answered Nov 11 '22 21:11

Ben Robinson