C# Record Type — Complete Guide
In this tutorial, you'll learn about C# Record Type. We cover key concepts, practical examples, and best practices.
You write a simple data class with a constructor, properties, Equals, GetHashCode, ToString, and Deconstruct. That is fifty lines of boilerplate for what should be five. C# records give you all of that with a single declaration.
Wrong
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
// Manual Equals, GetHashCode, ToString, Deconstruct...
}
Output: Reference equality by default. Two Person objects with identical names are not equal unless you write Equals manually.
Right
public record Person(string FirstName, string LastName);
Usage:
var p1 = new Person("Alice", "Smith");
var p2 = new Person("Alice", "Smith");
Console.WriteLine(p1 == p2); // True (value equality)
Console.WriteLine(p1); // Person { FirstName = Alice, LastName = Smith }
var (first, last) = p1; // Deconstruction
Output: True and Person { FirstName = Alice, LastName = Smith }.
Records give you value-based equality, built-in ToString, deconstruction, and with expressions for non-destructive mutation.
Prevention
- Use
recordinstead ofclassfor data transfer objects and view models. - Use
record structfor small, immutable value types. - Use
readonly record structfor zero-allocation immutable values. - Use
withexpressions to create modified copies without mutation. - Add validation in the primary constructor if you need invariants.
- Consider positional records for simple DTOs and nominal records (
record Foo { ... }) when you need additional methods or computed properties.
Common Mistakes with record type
- Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
- Using
returnto exit a function early instead of wrapping a pure value in the monad - Mixing let bindings with <- bindings in do notation, producing type errors
These mistakes appear frequently in real-world CSHARP code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Records are used across DodaTech products including Doda Browser for immutable configuration objects. For more, visit DodaTech.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro