C# Records vs Classes: What's the Difference?

C# records and classes can both represent objects, but they are designed with different goals. Classes are the traditional choice for objects with identity and mutable state, while records are especially useful for data-centric models where value-based equality is important.


đŸˇī¸ A Simple Class

public class Customer
{
    public string Name { get; set; }
    public int Age { get; set; }
}

Two class instances are normally compared by reference unless equality is explicitly implemented.


đŸ“Ļ A Simple Record

public record Customer(string Name, int Age);

Records provide compiler-generated value-oriented equality based on their data.

var a = new Customer("Dhilip", 31);
var b = new Customer("Dhilip", 31);

Console.WriteLine(a == b); // True

âš–ī¸ Equality Is the Big Difference

For many record scenarios, two objects containing the same values are considered equal. A normal class does not behave that way by default.

public class Product
{
    public int Id { get; set; }
}

var p1 = new Product { Id = 10 };
var p2 = new Product { Id = 10 };

Console.WriteLine(p1 == p2); // False

🔄 Non-Destructive Updates with with

Records work particularly well with the with expression:

var original = new Customer("Dhilip", 31);
var updated = original with { Age = 32 };

The original record remains unchanged while a new value is produced.


🧊 Records and Immutability

Records are not automatically immutable in every possible form, but positional records naturally encourage immutable-style models.

public record Customer(string Name, int Age);

This is particularly convenient for DTOs, messages, configuration snapshots, and other data-transfer scenarios.


🧩 When Should You Use a Class?

đŸŽ¯ When Should You Use a Record?


🧠 Quick Rule

If identity matters, start by considering a class. If the values are the important part, consider a record.

For more C# fundamentals, visit đŸ’ģ C# Tutorials.

🤖 AlgoLassi Assistant Have a question about this tutorial?

Ask AlgoLassi and get an answer plus the tutorials worth studying next.

Ask a question

đŸ’Ŧ Comments

Sign in with Google to publish immediately, or comment anonymously and wait for approval.

Comments will appear here when available.