When the general parameter will never be zero

In the general GetHashCode(T foo) method, I check if foo null . However, I just stumbled upon Reshar's strange warning.

In the following code, can foo never be null ?

 private class FooComparer<T> : IEqualityComparer<T> where T: Foo { public int GetHashCode(T foo) { // resharper warning: "Expression is always false" if (Object.ReferenceEquals(null,foo)) return 0; // ... calculate hash } } 

However, as far as I can tell, it’s completely legal:

 Foo foo = null; var fooComparer = new FooComparer<Foo>(); int hash = fooComparer.GetHashCode(foo); 
+4
source share
2 answers

The IEqualityComparer<T>.GetHashCode has a [NotNull] contract for its parameter, because it has implementations that throw an exception when null provided as an argument.

If you want to use FooComparer<T>.GetHashCode directly and safely for null exceptions as an argument, you can annotate it like this:

 public int GetHashCode([JetBrains.Annotations.CanBeNull] T foo) { // resharper warning: "Expression is always false" if (Object.ReferenceEquals(null,foo)) return 0; // ... calculate hash } 

However, the analysis for [Not-Null] parameters should be improved. This error exists for similar code at http://youtrack.jetbrains.com/issue/RSRP-304111

+5
source

The MSDN for IEqualityComparer<T>.GetHashCode Method says:

Exceptions:

ArgumentNullException The obj type is a reference type, and obj is null .

This means that calling GetHashCode<T>(T obj) with a null parameter violates the IEqualityComparer<T> contract.

I assume Resharper assumes that callers adhere to this contract and therefore never go null .

+4
source

Source: https://habr.com/ru/post/1434587/


All Articles