AssignNullToNotNullAttribute inspection and TryGetValue pattern

When I use Dictionary.TryGetValue() to check, whether there is particular item in dictionary and handle false result with assigning new value to out variable - AssignNullToNotNullAttribute inspection (like the other inspections of this kind) treats result variable sa NotNull, and it is correct behaviour.
Here is a sample:
sample.PNG
As we see, "value" usage fires inspection in TestMethod2 and does not in TestMethod1 - this means that ReSharper "knows" convention of TryGetValue method. But when I use such a pattern in my one code (creating TryGetSomething methods in my one classes) it results with false positive higlightings in my code. Is there a way to mark my own TryGetSomething methods by some kind of attribute or extend ReSharper knowledge with pluging to fix such false positive higlightings?

4 comments
Comment actions Permalink

It's nothing to do with the TryGetValue method.

In TestMethod1, you're assigning the value variable within the body of the "if" statement. In TestMethod2, you are not; if the key is not found in the dictionary, value will be null.

0
Comment actions Permalink

Thank you for answer, but my question was quite different - there is correct behaviour of inspection in that picture. But it works so only for Distionary.TryGetValue() method and my question is "How to achive such a behaviour for my SomeMyClass.TryGetValue() method?". I am sorry if my picture distorts my question.

0
Comment actions Permalink

Actually, I think the Dictionary.TryGetValue example is a bug. It's quite possible for the key to exist within the dictionary, but for the associated value to be null, in which case a null value will be passed to your [NotNull] parameter.

var dictionary = new Dictionary<string, string> { { "Test", null } };

string value;
if (!dictionary.TryGetValue("Test", out value)) value = "42";

Console.WriteLine(value == null ? "-NULL-" : value);
// Output: -NULL-


If you want to reproduce the (incorrect) behaviour with your own method, I suspect you'll need to use the ContractAnnotationAttribute.

0
Comment actions Permalink

Thanks a lot! It's just the answer I need. Regarding to the case of storing nulls in dictionary - it's possible, but it's not so in my code, thus it's completely works for me.

0

Please sign in to leave a comment.