Link to home
Start Free TrialLog in
Avatar of mikha
mikhaFlag for United States of America

asked on

Linq query exception

I have code block like this

private bool isupdated () {
   return books.where(x=> !IsNullOrEmpty(x.edition.version))
.any(x=>x.isNew);
}

here books is a ICollection<Books> books and book class has Edition as its private members along with others.

example is contrived for this question .

I get exception executing the function above and debugging that turns out due to some bad data the edition is null for one of the books , which shouldn’t be.

as a temporary fix I put in a check in the where clause above to check for edition
like below -
 return books.where(x=> x.edition != null && !IsNullOrEmpty(x.edition.version))


but I get the same exception that edition is null.

shouldn’t this check prevent it ?
Avatar of gr8gonzo
gr8gonzo
Flag of United States of America image

I'm assuming you have your own "IsNullOrEmpty" method, since that's typically a String method, called like this: String.IsNullOrEmpty(value).

That said, your "temporary fix" looks like the correct fix to me. When you have this:
IsNullOrEmpty(x.edition.version)

...the .NET engine is NOT calling IsNullOrEmpty() on each piece of the path. Instead, it's:
1. Accessing object "x"
2. Accessing the "edition" object inside of "x"
3. Accessing the "version" property inside of the "edition" object
4. Finally, it's running IsNullOrEmpty() on the value of "version"

So if edition is null, then when it gets to step 3, it ASSUMES that edition is a valid object that has a "version" property. If "edition" is null, then it gives you that because it can't access the "version" property of null.

That's why your temporary fix should work - the condition and the && should ensure edition is NOT null before continuing to the next condition (checking version).

So I don't quite see how you would get the same exception that edition is null unless maybe the exception is being thrown on a different line or it's just a very -similar- exception, or else we're not seeing all the code. So you should double-check the call stack when the exception is thrown and make sure it's truly being thrown from this particular line.
This question needs an answer!
Become an EE member today
7 DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform.
View membership options
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.