开发者

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

开发者 https://www.devze.com 2023-01-29 03:52 出处:网络
This code outputs True. using System; using System.C开发者_如何学JAVAollections.Generic; public class Default

This code outputs True.

using System;
using System.C开发者_如何学JAVAollections.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


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.


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

Other implementations of ICollection<T> might not allow nulls.

Whether this is the case or not, there's no reason why the ReSharper ruleset couldn't be refined to not flag this as a potential error.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号