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
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With