Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReSharper - Possible 'System.NullReferenceException' after Any

I'm using ReSharper Ultimate 2016.2, but I have seen this in previous versions as well. ReSharper will give me a warning saying Possible 'System.NullReferenceException' when I use FirstOrDefault after Any. Example below:

Foo[] items = GetItems();
var myName = "MyName";
if (items.Any(x => x.Name == myName))
{
    var item = items.FirstOrDefault(x => x.Name == myName);
    var name = item.Name; // Possible 'System.NullReferenceException'
}

Is the warning correct, or is the code above safe?

I know that I can disable the warning, but that's not the point. I want to make sure that there's no chance for that NullReferenceException to occur. Since I first check with Any, then FirstOrDefault should return one item. Or am I missing something?

The code above is simply a MCVE.

UPDATE:

As mentioned in the comments, the code can be optimized (and simplified). The question is not how to fix the problem in the code. But if there actually can occur a NullReferenceException, as ReSharper states?

like image 283
smoksnes Avatar asked Jan 22 '26 14:01

smoksnes


1 Answers

It is because of FirstOrDefault. It returns NULL for classes, if the condition does not match. ReSharper does not take the Any in account at this point.

You should replace it with a call to First

like image 136
Geiserich Avatar answered Jan 27 '26 00:01

Geiserich