Consider the following code:
IEnumerable<int> xx = null;
var tt = xx?.Where(x => x > 2).Select(x => x.ToString());
It assigns null
to tt
.
The question is: why does it work properly?
I thought I must use ?.
before Select as ?.Where(...)
returns null
.
Besides, if I split the second line into two separate lines:
IEnumerable<int> xx = null;
var yy = xx?.Where(x => x > 2);
var zz = yy.Select(x => x.ToString());
There will be the ArgumentNullException
on the third line as yy == null
.
What's the magic? :)
If this is because of short-circuiting, I've never thought that it can act like this.
WHERE
doesn't return null - it will return emptyIEnumerable<T>
- so it can't be null. You might have been thinking aboutFirstOrDefault()
– MercuricWhere
isn't even invoked. – Okeechobeeyy
in the second block is null. – ExpendableWhere
doesn't get called becausexx
is null. – Boylevar tt = (xx?.Where(x => x > 2)).Select(x => x.ToString())
– Ashtonashtonunderlynexx?.Where(x => x > 2).Select(x => x.ToString()).First().Length.GetHashCode();
– Expendable