ReSharper 5.x, HashSet Contains () and "Possible" null assignment ",

This code displays True .

 using System; using System.Collections.Generic; public class Default { public static void Main(string[] args) { HashSet<string> foo = new HashSet<string>(); foo.Add(null); Console.WriteLine(foo.Contains(null)); } } 

null in my call to Contains () has a blue curve below it with the following warning:

Possible assignment of 'null' to an object with the attribute 'NotNull'

When I pause ReSharper, the warning disappears.

Why does this warning occur? Given that I can add null to a HashSet, what has broken that I want to check the null value in a HashSet?

EDIT: .NET 3.5, VS2010

+4
source share
2 answers

I would say that this is a bug in Resharper. The HashSet<T> created to handle null values. This can be seen from consideration of the code in the reflector. In particular, the InternalGetHashCode method, which has an explicit check for null and provides a default hash code of 0.

In the case where this could potentially cause a problem, for user instances of IEqualityComparer<T> , a HashSet<T> is passed that do not take into account null values. I would say this is pretty rare, but since null checks are part of the standard equality pattern for reference types in .Net.

Note. To be clear, I certainly do not encourage people to add null to their collection. I would actually encourage the opposite. Just pointing out that for some reason HashSet<T> explicitly allows this scenario.

+3
source

I suspect this may be because the HashSet<T>.Contains is an implementation of ICollection<T>.Contains .

Other implementations of ICollection<T> may not allow null.

If this is true or not, there is no reason why the ReSharper rule set cannot be refined so as not to flag it as a potential error.

0
source

All Articles