Search code examples
c#gethashcodevaluetuple

What does the C# syntax mean (parentheses with properties followed by dot and method call) in C# when override GetHashCode()?


When overriding GetHashCode() for one of my classes, I found this code in the documentation https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/how-to-define-value-equality-for-a-type:

public override int GetHashCode() => (X, Y, Z).GetHashCode();

This is the first time I've encountered such syntax. I tried to Google it by describing it, but in vain.

My questions are:

  1. What does the full code look like if not using this syntax?

  2. If X, Y and Z are classes, and X is null, is this code safe to use?


Solution

  • (X, Y, Z) creates a value tuple with 3 elements. Its type is ValueTuple<T1, T2, T3>. You are simply calling GetHashCode on that ValueTuple<T1, T2, T3>.

    GetHashCode does not throw an exception even if any tuple elements are null. See the implementation here.

    If you don't want to use the tuple syntax, you can write

    ValueTuple.Create(X, Y, Z)
    

    instead.