[NotNull] Annotation for collection items

In most cases my collections never have null elements. So when iterating over them (either with "foreach" or with LINQ queries) Resharper displays to many false positives.

It would be nice to have a special annotation for collections to say that all items can never be null.

The best example for it is the Dictionary<K,V>.Keys collection. A key in the dictionary can never be null, but the ReSharper doesn't know it.

Is there a way to extend or improve the analysis engine?

Michael Damatov
prodot GmbH

4 comments
Comment actions Permalink

There is [ItemNotNull] but it doesn't work for Dictionary.

https://youtrack.jetbrains.com/issue/RSRP-463007

0
Comment actions Permalink

Ideally it would be possible to place an [ItemNotNull] attribute on the class definition, which could be used on classes that implemented IEnumerable<T>. 

When creating my own collection classes (i.e. implementing ICollection<T>), the built-in annotations automatically annotate [CanBeNull] on methods. For methods such as Contains, Remove, etc, it is trivial to add my own:

[ContractAnnotation("item:null => false")]

...but for methods like Add where I annotate with [ItemNotNull], it emits warnings about a mismatch between nullability. While this can obviously be suppressed, or even disabled altogether, I find this approach feels like a workaround, and not a clean solution to the issue. I feel being able to use annotations to clearly convey intent should be sufficient without the need to suppress warnings would be the best approach.

0
Comment actions Permalink

Nowadays you should use C# Null Reference Types which solve this issue.

0
Comment actions Permalink

You might be in a position not having the pleasure to use the most recent framework. A customer could have its reasons to use an older .NET Framework version.

0

Please sign in to leave a comment.