Created
July 8, 2025 02:43
-
-
Save emonarafat/52a511ab1284b50f163440524364fffe to your computer and use it in GitHub Desktop.
Examples of correct and incorrect usage of C# record types in real-world .NET projects — from immutability principles to EF Core gotchas.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // ❌ Misuse of Records in .NET — Don't Do This | |
| public record User | |
| { | |
| public string Name { get; set; } | |
| public int Age { get; set; } | |
| } | |
| // This is mutable — which defeats the purpose of records | |
| var user = new User { Name = "John", Age = 30 }; | |
| user.Age = 31; // Mutation warning! | |
| // ✅ Preferred: Immutable Record Pattern | |
| public record User(string Name, int Age); | |
| // Use with-expression for safe value mutation | |
| var updatedUser = user with { Age = 32 }; | |
| // ✅ Value Object Example — Good use of Record | |
| public record Money(decimal Amount, string Currency); | |
| // ❌ Don't use Records as EF Core Entities | |
| // EF Core needs identity tracking; records override equality | |
| public class Product // ← use class, not record | |
| { | |
| public int Id { get; set; } | |
| public string Name { get; set; } | |
| } | |
| // Summary: | |
| // - Use `record` for DTOs, configs, and value objects. | |
| // - Avoid `record` for EF Core or mutable models. | |
| // - Benchmark before switching to `record struct` in hot paths. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment