📦 Value Objects Made Easy
DTOs with 50 lines of boilerplate? Equals(), GetHashCode(), ToString()? Record types (C# 9+) are immutable, value-based, with auto-generated methods. One line replaces 50.
Traditional Class vs Record
// ❌ Traditional class - Lots of boilerplate
public class PersonClass
{
public string Name { get; init; }
public int Age { get; init; }
public PersonClass(string name, int age)
{
Name = name;
Age = age;
}
// Manual Equals
public override bool Equals(object? obj)
{
if (obj is not PersonClass other) return false;
return Name == other.Name && Age == other.Age;
}
// Manual GetHashCode
public override int GetHashCode()
{
return HashCode.Combine(Name, Age);
}
// Manual ToString
public override string ToString()
{
return $"PersonClass {{ Name = {Name}, Age = {Age} }}";
}
// Manual copy with changes
public PersonClass WithAge(int newAge)
{
return new PersonClass(Name, newAge);
}
}
// 40+ lines for simple data object!
// ✅ Record - One line!
public record Person(string Name, int Age);
// That's it! Auto-generates:
// - Constructor
// - Properties (init-only)
// - Equals() and GetHashCode() (value-based)
// - ToString()
// - Deconstruct()
// - With expressions
🎯 Record Features
public record Person(string Name, int Age);
// Value-based equality
var person1 = new Person("Alice", 30);
var person2 = new Person("Alice", 30);
Console.WriteLine(person1 == person2); // True! (value equality)
// With classes: False (reference equality)
// Auto ToString()
Console.WriteLine(person1); // Person { Name = Alice, Age = 30 }
// With expressions (non-destructive mutation)
var person3 = person1 with { Age = 31 };
Console.WriteLine(person3); // Person { Name = Alice, Age = 31 }
// person1 unchanged (immutable)
// Deconstruction
var (name, age) = person1;
Console.WriteLine($"{name} is {age}"); // Alice is 30
// Pattern matching
var message = person1 switch
{
{ Age: < 18 } => "Minor",
{ Age: >= 18 and < 65 } => "Adult",
_ => "Senior"
};
Record vs Record Struct vs Class
// Record (reference type, immutable by default)
public record Person(string Name, int Age);
// Record struct (value type, C# 10+)
public record struct Point(int X, int Y);
// Class (reference type, mutable)
public class PersonClass
{
public string Name { get; set; }
public int Age { get; set; }
}
// When to use what?
// Record: DTOs, value objects, immutable data
// Record struct: Small data (< 16 bytes), high-performance scenarios
// Class: Entities with behavior, mutable state
Advanced Record Features
// Additional properties and methods
public record Person(string Name, int Age)
{
// Computed property
public string DisplayName => $"{Name} ({Age})";
// Validation
public Person
{
if (Age < 0) throw new ArgumentException("Age cannot be negative");
}
// Additional methods
public bool IsAdult() => Age >= 18;
}
// Inheritance (records can inherit from records)
public record Employee(string Name, int Age, string Department)
: Person(Name, Age);
var emp = new Employee("Bob", 25, "IT");
Console.WriteLine(emp);
// Employee { Name = Bob, Age = 25, Department = IT }
// With expression works with derived records
var emp2 = emp with { Department = "HR" };
🌐 Perfect for DTOs
// API Request/Response DTOs
public record CreateUserRequest(
string Email,
string Name,
string Password
);
public record UserResponse(
int Id,
string Email,
string Name,
DateTime CreatedAt
);
// API Controller
[HttpPost("users")]
public async Task CreateUser(CreateUserRequest request)
{
var user = await _userService.CreateAsync(request);
return new UserResponse(
user.Id,
user.Email,
user.Name,
user.CreatedAt
);
}
// Clean, immutable, perfect for data transfer
Positional vs Nominal Records
// Positional record (concise)
public record Person(string Name, int Age);
// Nominal record (traditional property syntax)
public record Person
{
public string Name { get; init; }
public int Age { get; init; }
}
// Mix both
public record Person(string Name, int Age)
{
public string Email { get; init; } = string.Empty;
public DateTime CreatedAt { get; init; } = DateTime.UtcNow;
}
var person = new Person("Alice", 30)
{
Email = "alice@example.com"
};
✅ Benefits of Records
- Less code: 90% less boilerplate than classes
- Immutable by default: Thread-safe, predictable
- Value semantics: Equality based on data, not reference
- With expressions: Easy non-destructive updates
- Pattern matching: Works beautifully with switch
- Auto ToString(): Great for debugging
💡 Best Practices
- Use for DTOs: API requests/responses, messages
- Use for value objects: Money, Address, Coordinate
- Add validation: In constructor or properties
- Keep immutable: Use init, not set
- Prefer positional: More concise for simple records
🎯 Real-World Example
// Domain value objects
public record Money(decimal Amount, string Currency)
{
public Money Add(Money other)
{
if (Currency != other.Currency)
throw new InvalidOperationException("Currency mismatch");
return this with { Amount = Amount + other.Amount };
}
}
public record Address(
string Street,
string City,
string State,
string ZipCode,
string Country
);
public record CustomerDto(
int Id,
string Name,
Address Address,
Money Balance
);
// Usage
var addr = new Address("123 Main St", "NYC", "NY", "10001", "USA");
var balance = new Money(1000m, "USD");
var customer = new CustomerDto(1, "Alice", addr, balance);
// Update address
var updated = customer with
{
Address = customer.Address with { City = "Boston" }
};
// Value equality
var addr2 = new Address("123 Main St", "NYC", "NY", "10001", "USA");
Console.WriteLine(addr == addr2); // True!
"Converted all DTOs from classes to records. Deleted 2000+ lines of boilerplate. Bugs related to mutable state disappeared. API responses now immutable, thread-safe. Should've used records from day one."
