Easier immutability with Init only properties in C# 9

C# 9 shipped with .NET 5 in November. One change included is init only properties which allow us to have immutable (non-changeable) classes without some of the downsides associated with pre C# 9 approaches.

As can be seen below in C# 8 we’d typically have getters with no setters which gives us immutability…great.. but it means we need a constructor and we can’t use the more shorthand object initializer (C# 3.0) syntax which many developers prefer.

In C# 9 we can use the init keyword which means we can get rid of the constructor and use shorthand object initialization.

This is a small but nice addition to the language and means developers don’t have to choose between ease of use and immutability.

Links

C# 9 Language Features | On .NET | Channel 9 (msdn.com)

What’s new in C# 9.0 – C# Guide | Microsoft Docs