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

c#, contains, hashset, null, resharper

Solution

I would say this is a bug in Resharper. The `HashSet<T>` type is constructed to handle `null` values. This is evident by examining the code in reflector. In particular the `InternalGetHashCode` method which has an explicit check for `null` and provides a default hash code of 0.

The one case where this could potentially turn up a problem is for custom `IEqualityComparer<T>` instances passed to the `HashSet<T>` which do not account for `null` values. I'd say this is fairly rare though as `null` checks are part of the standard equality pattern for reference types in .Net.

Note: To be clear, I'm certainly not encouraging people to add `null` to their collection. I would in fact encourage the opposite. Just pointing out that for whatever reason `HashSet<T>` seems to explicitly allow for this scenario.

Problem

This code outputs `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)); } } ``` The `null` in my Contains() call has a blue squiggle under it, with the following warning: Possible 'null' assignment to entity marked with 'NotNull' attribute When I suspend ReSharper, the warning goes away. Why is this warning occurring? Given that I can add null to a HashSet, what's broken about my wanting to check for null in a HashSet? EDIT: .NET 3.5, VS2010

Original source