Definition

A record in C# is a class or struct that provides special syntax and behavior for working with data models. The record modifier instructs the compiler to synthesize members that are useful for types whose primary role is storing data. These members include an overload of ToString() and members that support value equality.

When to use

Consider using a record in place of a class or struct in the following scenarios:

  • You want to define a data model that depends on value equality.
  • You want to define a type for which objects are immutable.
Record Types

Declaration:

 // Value type: Stores all values
public record Point(int X, int Y)
{
  public double Slope() => (double)Y / (double)X;
}

public static void Main()
{
  Point pt = new Point(1, 1);
  var pt2 = pt with { Y = 10 };
  double slope = pt.Slope();

  Console.WriteLine($"The two points are {pt} and {pt2}"); // The two points are Point { X = 1, Y = 1 } and Point { X = 1, Y = 10 }

  Console.WriteLine($"The slope of {pt} is {slope}"); //The slope of Point { X = 1, Y = 1 } is 1
}
Declaration
interface IEquatable<T>
{
  bool Equals(T obj);
}

public class Car : IEquatable<Car>
{
  public string? Make { get; set; }
  public string? Model { get; set; }
  public string? Year { get; set; }

  // Implementation of IEquatable<T> interface
  public bool Equals(Car? car)
  {
    return (this.Make, this.Model, this.Year) ==
      (car?.Make, car?.Model, car?.Year);
  }
}
Declaration
// Declare the generic class.
public class GenericList<T>
{
  public void Add(T item) { }
}

public class ExampleClass { }

class TestGenericList
{
  static void Main()
  {
    // Create a list of type int.
    GenericList<int> list1 = new();
    list1.Add(1);

    // Create a list of type string.
    GenericList<string> list2 = new();
    list2.Add("");

    // Create a list of type ExampleClass.
    GenericList<ExampleClass> list3 = new();
    list3.Add(new ExampleClass());
  }
}
Declaration
var v = new { Amount = 108, Message = "Hello" };

// Rest the mouse pointer over v.Amount and v.Message in the following
// statement to verify that their inferred types are int and string.
Console.WriteLine(v.Amount + v.Message);