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:
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?
Please sign in to leave a comment.
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.
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.
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.
If you want to reproduce the (incorrect) behaviour with your own method, I suspect you'll need to use the ContractAnnotationAttribute.
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.