Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReSharper: Null check is always false warning

Using ReSharper 8.2 I get a warning ("Expression is always false") for the null check in

public bool TryGetValue(TKey key, out TValue value)
{
  if (key == null)

from NHibernate NullableDictionary. Why is this? When I try it with

class Test<T> where T : class

then I don't get the warning for null checks on T variables as expected.

Edit: To make things easier here is the class signature of the linked source:

public class NullableDictionary<TKey, TValue> : IDictionary<TKey, TValue> where TKey : class
like image 630
user764754 Avatar asked Dec 20 '14 14:12

user764754


1 Answers

It's occurring because the class implements IDictionary<TKey, TValue>; the warning disappears if you (temporarily) delete the interface portion of the class signature.

Since the "key" in the standard System.Collections.Generic.Dictionary class can never be null (it throws an ArgumentNullException), I'd say ReSharper is making an incorrect assumption.


Testing the behavior:

I tested the class in an otherwise empty project and tried it out. Although ReSharper grayed out all the code, it definitely still executed at runtime.

The gray text indicates ReSharper believes the logic will always drop through to the else block, but that's clearly not the case when you use it.

enter image description here


A fix, using Annotations:

To get around the issue of ReSharper assuming by default that the key cannot be null, you could use the JetBrains Annotations.

Add a reference to the JetBrains Annotations assembly. For me, this was the location:

C:\Program Files (x86)\JetBrains\ReSharper\v8.2\Bin\JetBrains.Annotations.dll

Then add a using directive to the top of the file where the class is:

using JetBrains.Annotations;

Now mark that parameter with the CanBeNull attribute and you'll see ReSharper no longer grays out the text:

public bool TryGetValue([CanBeNull] TKey key, out TValue value)

enter image description here

like image 52
Grant Winney Avatar answered Oct 18 '22 14:10

Grant Winney