0Pricing
C# Academy · Lesson

Record-like types & value-based equality (pattern)

Implement value-based equality like records: override Equals/GetHashCode, implement IEquatable , add ==/!= operators, and keep types immutable.

Record-like types & value-based equality (pattern) is a free C# Academy lesson on CoddyKit — lesson 2 of 3. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C# Academy learning path, one of 3 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Record-like overview

Goal: Make objects compare by value (record-like) in C# 6.

  • Immutable data
  • Override Equals and GetHashCode
  • Implement IEquatable<T>
  • Optional: define ==/!=

Reference equality issue

Classes compare by reference by default. Two objects with the same data are not equal.

using System;

public class PersonRef
{
  public string First;
  public string Last;
}

public class Program
{
  public static void Main(string[] args)
  {
    PersonRef a = new PersonRef { First = "Ada", Last = "Lovelace" };
    PersonRef b = new PersonRef { First = "Ada", Last = "Lovelace" };

    Console.WriteLine("Reference Equals? " + object.ReferenceEquals(a, b)); // false
    Console.WriteLine("== (default)? " + (a == b)); // false (same as ReferenceEquals for classes)
  }
}

Record-like class pattern

Make the class immutable and implement IEquatable<T>, Equals, GetHashCode, and ==/!= so equality depends on data.

using System;

// Immutable, value-based equality
public sealed class Person : IEquatable<Person>
{
  public string First { get; private set; }
  public string Last  { get; private set; }

  public Person(string first, string last)
  {
    if (string.IsNullOrEmpty(first)) throw new ArgumentException("first");
    if (string.IsNullOrEmpty(last))  throw new ArgumentException("last");
    First = first; Last = last;
  }

  // "With" helper for copy-on-change
  public Person WithFirst(string first) { return new Person(first, Last); }
  public Person WithLast(string last)   { return new Person(First, last); }

  public bool Equals(Person other)
  {
    if (object.ReferenceEquals(other, null)) return false;
    if (object.ReferenceEquals(this, other)) return true;
    return string.Equals(First, other.First) && string.Equals(Last, other.Last);
  }

  public override bool Equals(object obj)
  {
    return Equals(obj as Person);
  }

  public override int GetHashCode()
  {
    unchecked
    {
      int h = 17;
      h = h * 31 + (First == null ? 0 : First.GetHashCode());
      h = h * 31 + (Last  == null ? 0 : Last.GetHashCode());
      return h;
    }
  }

  public static bool operator ==(Person a, Person b)
  {
    if (object.ReferenceEquals(a, b)) return true;
    if ((object)a == null || (object)b == null) return false;
    return a.Equals(b);
  }

  public static bool operator !=(Person a, Person b) { return !(a == b); }
}

public class Program
{
  public static void Main(string[] args)
  {
    Person p1 = new Person("Ada", "Lovelace");
    Person p2 = new Person("Ada", "Lovelace");
    Console.WriteLine("Value Equals? " + (p1 == p2)); // true
    Person p3 = p1.WithLast("King");
    Console.WriteLine("After With: " + (p1 == p3));   // false
  }
}

Struct equality pattern

Structs compare by fields via ValueType.Equals by default, but implementing IEquatable<T> makes intent and hashing clear.

using System;

public struct Point2 : IEquatable<Point2>
{
  public int X;
  public int Y;

  public Point2(int x, int y) { X = x; Y = y; }

  public bool Equals(Point2 other)
  {
    return X == other.X && Y == other.Y;
  }

  public override bool Equals(object obj)
  {
    if (!(obj is Point2)) return false;
    return Equals((Point2)obj);
  }

  public override int GetHashCode()
  {
    unchecked { return (X * 397) ^ Y; }
  }

  public static bool operator ==(Point2 a, Point2 b) { return a.Equals(b); }
  public static bool operator !=(Point2 a, Point2 b) { return !a.Equals(b); }
}

public class Program
{
  public static void Main(string[] args)
  {
    Point2 a = new Point2(1, 2);
    Point2 b = new Point2(1, 2);
    Console.WriteLine("Struct value equality: " + (a == b)); // true
  }
}

Value objects as keys

When a value object is a Dictionary key, correct Equals/GetHashCode ensures lookups succeed.

using System;
using System.Collections.Generic;

public sealed class Email : IEquatable<Email>
{
  public string Address { get; private set; }
  public Email(string address)
  {
    if (string.IsNullOrEmpty(address)) throw new ArgumentException("address");
    Address = address.Trim().ToLowerInvariant();
  }

  public bool Equals(Email other)
  {
    if (object.ReferenceEquals(other, null)) return false;
    return Address == other.Address;
  }

  public override bool Equals(object obj) { return Equals(obj as Email); }

  public override int GetHashCode()
  {
    return Address == null ? 0 : Address.GetHashCode();
  }
}

public class Program
{
  public static void Main(string[] args)
  {
    Dictionary<Email, string> owners = new Dictionary<Email, string>();
    owners[new Email("User@Mail.com")] = "Ada";
    Console.WriteLine(owners.ContainsKey(new Email("user@mail.com"))); // true
  }
}

Equality checklist

Checklist:

  • Keep data immutable.
  • Override Equals and GetHashCode.
  • Implement IEquatable<T> for type-safe, fast compares.
  • Add ==/!= for convenience.
  • Use consistent fields in both equality and hashing.

Record-like equality requirement

Quick check: For a class to behave like a value (record-like) in C# 6, what must you do?

Recap

Recap: In C# 6 you build record-like types by hand: immutable data, IEquatable<T>, correct Equals/GetHashCode, and (optionally) ==/!=. Use them safely in sets and dictionaries.

Frequently asked questions

Is the “Record-like types & value-based equality (pattern)” lesson free?

Yes — the full text of “Record-like types & value-based equality (pattern)” is free to read here on the web, and the C# Academy course includes 3 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C# Academy course, upgrade to CoddyKit PRO.

What will I learn in “Record-like types & value-based equality (pattern)”?

Implement value-based equality like records: override Equals/GetHashCode, implement IEquatable , add ==/!= operators, and keep types immutable. You practise C# Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start C# Academy?

No prior experience is required. C# Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 3, so you can start here or from the beginning and move at your own pace.

How long does the “Record-like types & value-based equality (pattern)” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this C# Academy lesson?

Yes. Every C# Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Structs: value semantics & immutability pattern
  2. Record-like types & value-based equality (pattern)
  3. Enums & [Flags]
← Back to C# Academy