Are C# 9 Records Immutable?

C# 9 has introduced the record keyword, and while it's a powerful tool for data management, it brings a common point of confusion: Are records truly immutable? 🤔

Here’s the scoop:

  • Positional Records (e.g., public record Employee(string Name, int Age);) are immutable by default. Once created, their properties cannot be changed. This design enhances data integrity and predictability—an essential feature for robust applications! 💪


  • But, the traditional class approach (e.g., public record EmployeeTraditional { public string Name { get; set; }; }) can be mutable! Here, you can change properties freely, which may lead to unexpected changes down the line. ⚠️


  • Want a middle ground? The init accessor lets you set properties at creation while keeping them immutable afterward. Perfect for scenarios where you want flexibility without compromising integrity!


As developers, it's crucial to understand these nuances to leverage the full potential of records. Let's clear the air: Records are immutably powerful, but how you define them determines their behavior!

Caution for 𝗨𝗻𝗶𝘁𝘆 𝗗𝗲𝘃𝗲𝗹𝗼𝗽𝗲𝗿𝘀: C# 9 init and record support comes with a few caveats!

Post a Comment

0 Comments