Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object reference not set to an instance while not being null

Tags:

c#

I'm getting some unexpected behavior in my process. I'm doing the following.

IEnumerable<Thing> things = ...;
IEnumerable<Thing> subset = things.Where(a => a.SomeFlag);
String info = "null: " + (subset == null);

The above works and info tells me that the object isn't null. So I wish to check the number of the elements in subset by this.

IEnumerable<Thing> things = ...;
IEnumerable<Thing> subset = things.Where(a => a.SomeFlag);
String info = "null: " + (subset == null);
String count = subset.Count();

Now I get an exception giving me the error message:

Object reference not set to an instance of an object.

What do I miss?!

like image 337
Konrad Viltersten Avatar asked Aug 11 '13 19:08

Konrad Viltersten


1 Answers

It's possible that one of the Thing's in subset is null. You can try this:

IEnumerable<Thing> subset = things.Where(a => a != null && a.SomeFlag);

Note that due to the way Linq's lazy evaluation, you won't get any exception you call .Where because all it's doing at that point is setting up a condition for filtering the elements of things. Only later when you call .Count is it actually evaluating the results.

Update: With the new null-condition operator in C# 6 (also called the safe navigation or 'Elvis' operator), we can do the same thing a bit more succinctly:

IEnumerable<Thing> subset = things.Where(a => a?.SomeFlag);
like image 162
p.s.w.g Avatar answered Sep 28 '22 01:09

p.s.w.g