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
Please sign in to leave a comment.
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:
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?
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".
Looks like this will be fixed in 8.1:
http://blogs.jetbrains.com/dotnet/2013/10/resharper-81-eap/