Immutability in .NET just got a LOT easier
C# records provide value-based equality, concise declarations, useful printing, deconstruction, and immutable copying, while record structs offer value-type behavior.
Transcript 1 topic
Create immutable objects
0:00If you're trying to create an immutable object in dot net, you're probably using private set or maybe no set at all. But there's a better way. The init keyword may be what you're looking for. Check out this class that uses private set. Now while external code can't make changes to those properties, the class itself can as you can see in that change name method.
Now we could fix that by removing the set accessor method altogether which leaves us with just setting that value in a constructor. But now we're tied to just using a constructor to instantiate this object. If you're like me, you love that new syntactic sugar that allows you to new things up with an object initializer. And that's what the init accessor method gives you. Check out this updated class where we replace the set with init.
Now the class can be initialized using an object initializer and we can mark properties nullable or required so that users of this class get that nice IntelliSense goodness. It's pretty sweet, right? Until next time.
Sign in to join in. Reading needs nothing.