C# Records

C# records are a new way of defining reference types that use value equality. They’re very helpful when you need an immutable data type, saving you from having to write readonly properties and overriding a bunch of equality methods.

For example, here’s an immutable class definition with value equality and a nicely formatted string output:

public class TeamClass
private readonly string _name;
private readonly int _yearFormed;
public TeamClass(string name, int yearFormed)
=> (_name, _yearFormed) = (name, yearFormed);

public string Name => _name;
public int YearFormed => _yearFormed;

public override string ToString() => $"TeamClass {{ "{{" }} Name = {Name}, YearFormed = {YearFormed} }}";

public override bool Equals(object obj)
return obj is TeamClass otherTeam
&& Name == otherTeam.Name
&& YearFormed == otherTeam.YearFormed;

public override int GetHashCode() => ToString().GetHashCode();

public static bool operator ==(TeamClass tc1, TeamClass tc2)
=> tc1.Equals(tc2);

public static bool operator !=(TeamClass tc1, TeamClass tc2)
=> !tc1.Equals(tc2);

And here’s the same functionality with a record:

public record TeamRecord(string TeamName, int YearFormed);

See the results with this code:

using System;

var team1 = new TeamClass("Team1", 1999);
var team2 = new TeamClass("Team1", 1999);

Console.WriteLine(team1 == team2);

var team3 = new TeamRecord("Team1", 1999);
var team4 = new TeamRecord("Team1", 1999);

Console.WriteLine(team3 == team4);

View code on GitHub

Leave a Reply

Your email address will not be published.