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.
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
)
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?
).
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 ??.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With