C# Tutorial · Object-Oriented C# · Lesson 14 of 22

C# Records, Structs and Enums

Immutable records with value equality, structs and enums.

Records

A record is a concise type for data with value equality, a readable ToString() and non-destructive mutation with with:

Example 1
var a = new Person("Ada", 36);
var b = new Person("Ada", 36);
Console.WriteLine(a);
Console.WriteLine(a == b);
var older = a with { Age = 37 };
Console.WriteLine($"{older.Name} {older.Age} / original {a.Age}");
var (name, age) = a;
Console.WriteLine($"{name} is {age}");

record Person(string Name, int Age);

Output

Person { Name = Ada, Age = 36 }
True
Ada 37 / original 36
Ada is 36

Run this on your computer — see “Get Started” for setup.

Enums

Example 2
var status = OrderStatus.Shipped;
Console.WriteLine($"{status} = {(int)status}");
Console.WriteLine(Enum.Parse<OrderStatus>("Paid"));
Console.WriteLine(string.Join(", ", Enum.GetNames<OrderStatus>()));
Console.WriteLine(status switch
{
    OrderStatus.Pending => "Waiting for payment",
    OrderStatus.Shipped => "On its way",
    _ => "Other",
});

enum OrderStatus { Pending, Paid, Shipped = 10, Delivered }

Output

Shipped = 10
Paid
Pending, Paid, Shipped, Delivered
On its way

Run this on your computer — see “Get Started” for setup.

structs are value types — good for small, immutable values like points or money.

Test yourself

Two records with the same property values — are they equal with ==?

  1. No, they're different objects
  2. Yes, records use value equality
Show answer

Answer: Yes, records use value equality