Search code examples
c#roslynroslyn-code-analysis.net-7.0code-generation

How to implement HashCode.Combine using SymbolEqualityComparer


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


Solution

  • 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.