Null coalesce interfering with LINQ FirstOrDefault?

I have some code which basically says:

var selected = collection.FirstOrDefault(foo => foo.Bar == value) ?? collection.FirstOrDefault(foo => foo.Bar == 0);

After this line, selected is null, and it shouldn't be. In the debugger in this case, foo.Bar is 0 on the only element in the collection, and value is 0. Neither expression should return null, yet selected is assigned null.

If I split the same code into two variables, and assign each side of the null coalesce to these, both are set to non-null values.

In case it matters, foo is a reference type, so FirstOrDefault should return null if it doesn't find an element satisfying the lamda.

Any ideas?

by djleni via /r/csharp

Leave a Reply