1

After updating packages to .net7 in roslyn code generation project, has error RS1024 Use 'SymbolEqualityComparer' when comparing symbols for IEqualityComparer implementation of GetHashCode()

public int GetHashCode([DisallowNull] TypeSymbolMetaType? obj) => System.HashCode.Combine(obj.TypeSymbol);

How to fix HashCode.Combine using SymbolEqualityComparer

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
  • 1
    Welcome to SO. What is `TypeSymbolMetaType`? Can you show more of your code? – Tim Schmelter Apr 26 '23 at 15:09
  • 2
    What the error message suggests would be using `public int GetHashCode([DisallowNull] TypeSymbolMetaType? obj) => SymbolEqualityComparer.Default.GetHashCode(obj.TypeSymbol);`, as [per docs](https://learn.microsoft.com/en-us/dotnet/api/microsoft.codeanalysis.symbolequalitycomparer.gethashcode?view=roslyn-dotnet) with some rationale explained [here](https://github.com/dotnet/roslyn-analyzers/issues/3427#issuecomment-604103434). – orhtej2 Apr 26 '23 at 15:16

1 Answers1

0

Assuming TypeSymbol is ISymbol then you don't need to use Combine in this example:

public int GetHashCode([DisallowNull] TypeSymbolMetaType? obj) => SymbolEqualityComparer.Default.GetHashCode(obj.TypeSymbol);

In case you want to combine multiple properties the use the result of the SymbolEqualityComparer.Default.GetHashCode:

public int GetHashCode([DisallowNull] TypeSymbolMetaType? obj) => 
        System.HashCode.Combine(
            SymbolEqualityComparer.Default.GetHashCode(obj.TypeSymbol).
            ...);

P.S.

In some cases you might need to use SymbolEqualityComparer.IncludeNullability.

Guru Stron
  • 102,774
  • 10
  • 95
  • 132