Tsallaka zuwa abun ciki
Justice Tech School

ToString, Equals and GetHashCode

Override ToString for text and Equals with GetHashCode for value comparison.

Example
Console.WriteLine(new P { Id = 1 });
Console.WriteLine(new P { Id = 1 }.Equals(new P { Id = 1 }));

class P
{
    public int Id;
    public override string ToString() => $"P#{Id}";
    public override bool Equals(object? o) => o is P p && p.Id == Id;
    public override int GetHashCode() => Id;
}

Exercise

Text of an object.

public override string () => "x";

Quiz Test

Why override GetHashCode with Equals?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.