ReSharper 8.0.1, Linq Where clauses and null checks

Is there any way to have R# understand the use of a linq where clause as a null check?I.E.  I have the following code:<code lang="c#">foreach( var item in collection.Where( item => item.Identity.HasValue ) ){     if( SomethingContainsItems( item.Identity.Value ) )     {           .           .           .      }}</code>and R# is complaining the <c>item.Identity.Value</c> is a possible NullReferenceException, which is impossible.ThanksDavid
4 comments
Comment actions Permalink

Without inspecting the implementation of the property, R# can't know for certain that your code won't throw an exception. For example, your property could be implemented as:

private int? _identity;

public int? Identity
{
   get
   {
      int? value = _identity;
      _identity = null;
      return value;
   }
}


In this case, the first call to the property would return a value, and the second call would return null. The item would pass the filter in the Where clause, and throw an exception in the body of the foreach block.

Since you know the property has a value, why not replace item.Identity.Value with item.Identity.GetValueOrDefault(), which will never throw an exception?

0
Comment actions Permalink
Yes I could, and should - I always seem to forget that function.  But while that will help in the specific case, it does not answer the bigger question - how to allow a linq query be known as performing a null check.  I see the same functionality when evaluating a collection, filtering out null objects via a where clause and trying to access them: <pre>internal sealed class Test {} List<Test> collectionOfTests = new List<Test> { null, new Test(), null, new Test() }; foreach( var test in collectionOfTests.Where( t => t != null ) ){                 Debug.Print( test.ToString() );} </pre>shows that test in the Debug.Print could be null.
0
Comment actions Permalink

Yes, that's annoying. It only seems to happen when you set the "Code Inspection / Settings / Assume entity value can be null" setting to "When entity doesn't have explicit NotNull attribute".

0
Comment actions Permalink

Looks like this will be fixed in 8.1:
http://blogs.jetbrains.com/dotnet/2013/10/resharper-81-eap/

Another complaint that’s been addressed relates to ReSharper complaining about values possibly being

null
in LINQ even when an explicit check has already been made. We’ve updated our LINQ nullness analysis so that the following code no longer triggers any complaints from ReSharper:

ReSharper 8.1 Nullness LINQ Analysis

0

Please sign in to leave a comment.