0

I am trying to check a type of IEnuemrable<SystemUser> for null.

I am using this piece of code

            var systemUsers = newActActivityPersons.SelectMany(x => x.Person.SystemUsers);
            if (systemUsers == null || !systemUsers.Any()) return ;

That isn't working. When I try to do something like systemUsers.ToArray() or systemUsers.ToList() I get a null exception. How can I check this for errors?

Ash
  • 5,786
  • 5
  • 22
  • 42
Train
  • 3,420
  • 2
  • 29
  • 59
  • it's not `systemUsers` that is null. what does the debugger say? – Cory Nelson Dec 07 '16 at 00:53
  • 1
    Your checking has no problem. Maybe newActActivityPersons is null. – Duc Filan Dec 07 '16 at 00:54
  • 1
    SelectMany does not return null so that check is redundant anyway. if `systemUsers.ToList()` is throwing a NRE, it's being nulled afterwards. Post a bigger chunk that shows what's happening between here and where you're getting the exception. – Saeb Amini Dec 07 '16 at 00:55
  • Duplicate shows how to do *what you are asking about*. Note that your post is likely has nothing to do with problem you have and comment from @SaebAmini is likely explanation. Feel free to ask new question with [MCVE] if you still have the problem. – Alexei Levenkov Dec 07 '16 at 00:59
  • systemUsers is not null, therefore systemUsers.Any() is not executed, therefore you get an exception after when you try to enumerate because you have a null returned by x.Person before trying to access .SystemUsers – Jonas Dec 07 '16 at 01:16

1 Answers1

1

One of the subsequent x.Person.SystemUsers could be null. .Any() returns true if there is one. If you then try to ToList() afterwards, you might find an x who's Person is null.

Check to make sure that x.Person isn't null before accessing a property on the object.

Justin Self
  • 6,137
  • 3
  • 33
  • 48