In C# 9.0, a new record
type is introduced which is a reference type that provides synthesized methods to provide value semantics for equality.
record
type immutable by default and make it easy to create immutable reference types in .NET.The record
keyword makes an object immutable and behaves like a value type.
public record Customer
{
public string LastName { get; }
public string FirstName { get; }
public Customer(string first, string last) => (FirstName, LastName) = (first, last);
}
You can also make the whole object immutable using the init
keyword on each property if you are using an implicit parameterless constructor.
public record Customer
{
public string LastName { get; init; }
public string FirstName { get; init; }
}
Records support inheritance and you can declare a new record derived from the base class.
public record Person
{
public string LastName { get; }
public string FirstName { get; }
public Person(string first, string last) => (FirstName, LastName) = (first, last);
}
public record Employee : Person
{
public string Title { get; }
public Employe(string first, string last, string title) : base(first, last) => Title = title;
}
By default, regular classes are considered equal when they share the same underlying reference.
Customer customer1 = new Customer
{
FirstName = "Mark",
LastName = "Upston"
};
Customer customer2 = new Customer
{
FirstName = "Mark",
LastName = "Upston"
};
Console.WriteLine(customer1.Equals(customer2)); // True