3

I am getting an unusual "NullReferenceException was unhandled by user code" error in this LINQ query:

List<UDIDInfo> d2Android = d2.Where(x.DeviceOS == (byte)DeviceOS.Android).ToList();

I went ahead and added a null check and am still getting the error

List<UDIDInfo> d2Android = d2.Where(x => x.DeviceOS != null && x.DeviceOS == (byte)DeviceOS.Android).ToList();

Note that (byte)DeviceOS.Android and d2 are both not null

Edit (Solution):

List<UDIDInfo> d2Android = d2.Where(x => x != null && x.DeviceOS != null && x.DeviceOS == (byte)DeviceOS.Android).ToList();
3
  • Are you sure it's linq-to-entities? What type is d2? Commented Nov 6, 2013 at 20:17
  • If d2 is null, what do you expect? Commented Nov 6, 2013 at 20:27
  • Possible duplicate of What is a NullReferenceException and how do I fix it? Commented Oct 4, 2015 at 9:09

2 Answers 2

8

What if x is null? That is, the enumerable d2 contains a null item.

Try the following. You shouldn't get any null reference exception.

List<UDIDInfo> d2Android = d2
    .Where(x => x != null)
    .Where(x => x.DeviceOS != null)
    .Where(x => x.DeviceOS == (byte)DeviceOS.Android)
    .ToList();
Sign up to request clarification or add additional context in comments.

5 Comments

If this is Linq-to-entities, then x can't be null.
@user2674389 That's probably true. I didn't even notice the LINQ-to-entities tag since there was no mention in the question.
Actually Tim's method worked; adding x != null short circuits the query. d2 is a List<T>
@OmarMeky Then the tag EntityFramework is wrong, since there is nothing related to EntityFramework.
Fair enough, I added it since the List came from an EF query but that's irrelevant
0

avoid the argument null exception in LINQ like below

Summaries = (from r in Summaries
          where r.Contains(SearchTerm)
          orderby r
          select r).ToArray();

In this case, if null passed to searchTerm you can check the null expression like below

Summaries = (from r in Summaries
          where string.IsNullOrEmpty(SearchTerm) ||r.Contains(SearchTerm)
          orderby r
          select r).ToArray();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.