📝 Records = Immutable Data
Classes are mutable. Records are immutable. Value-based equality, concise syntax, data-centric.
❌ Class (Mutable)
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
✅ Record (Immutable)
public record Person(string Name, int Age);
📝 Record Features
// Positional record
public record Person(string Name, int Age);
// Creating instances
var person1 = new Person("Alice", 30);
var person2 = new Person("Alice", 30);
// Value-based equality
Console.WriteLine(person1 == person2); // True
// With expression (copy with changes)
var person3 = person1 with { Age = 31 };
// Record with methods
public record Person(string Name, int Age)
{
public string Greeting => $"Hello, my name is {Name}";
public bool IsAdult() => Age >= 18;
}
// Record with properties
public record User
{
public string Name { get; init; }
public int Age { get; init; }
public string Email { get; init; }
}
// Record with validation
public record Product
{
public string Name { get; init; }
public decimal Price { get; init; }
public Product(string name, decimal price)
{
if (string.IsNullOrEmpty(name))
throw new ArgumentException("Name required");
if (price < 0)
throw new ArgumentException("Price must be positive");
Name = name;
Price = price;
}
}
// Record Use Cases
- Data Transfer Objects (DTOs)
- API responses
- Immutable data
- Value-based equality needed
- Brief data containers
✅ When to Use Records
- Data Transfer Objects (DTOs)
- API responses
- Immutable data
- Value-based equality needed
- Brief data containers
"Records are perfect for immutable data. Value equality, concise syntax. Essential for modern C#."
