C# 7.2 – Let’s talk about readonly structs

With the Roslyn update, this was the first time that C# received minor versions instead of only major ones. Roslyn helped the designers of the language to move in different leaps and provide more stuff in shorter time with minor versions.
In this article we will be discussing about a feature introduced in C# 7.2, the readonly structs

Any struct can have public properties, private properties accessors etc. For our examples we will start with the following struct.

As you can see, all properties can be publicly accessible and edited. Heck, we even have access to the content of this and change it to another instance of the same struct.
Well this is where the readonly keyword comes in place. If add it in the struct definition like the following

The following screenshot shows the result of compiling the above code

So what happened? Well by adding the readonly keyword to our struct we have basically made every single property readonly, including the value of this.

The only way to make our code compile is to make everything readonly, which means our struct would look like this

So adding readonly removes any possibility of unintended assignment or value change inside or outside an instance of a struct. One thing you need to beware of though, is if you tend to use the parameterless constructor along with property assignment like so

or like the following

while the default parameterless constructor for the struct will still be available for you to call, assigning any property will result in a compilation error as the properties are readonly. So any call to the parameterless constructor of the struct, will set the properties to their default values and they will never be changed for the lifetime of the struct instance.

So in conclusion, this will help showing your intent a lot easier as you can define from the start that this struct is immutable and non-editable.

Please follow and like us:

    C# 7.2 – Let’s talk about readonly structs - How to Code .NET

    […] by /u/macrian [link] […]

    Professional Development – 3/11/2019 – 3/17/2019 – The Software Mentor

    […] C# 7.2 – Let’s Talk About Readonly Structs […]

Leave a Reply