[C# 7.2] Readonly Structs

Lets look at some new features recently release with the C# 7.2 minor releases, I will explain what it was trying to solve and how.

A bit of background, with structs in C#, its possible to expose public properties as well as setting private properties, the example below shows its structure:-

public struct Document
{
public string Title { get; set; }
public string Author { get; set; }

public Document( string title, string author )
{
Title = title;
Author = author;
}

public void ChangeDocument(Document newDoc){
this = newDoc;
}
}

 So from this we can see that it causes the struct to be in a mutable state whereby we allow the public properties to be modified using the "this" key.

Moving for a more immutable solution we can leverage the new C# 7.2 feature and decorate the struct with readonly.

public readonly struct Document
{
public string Title { get; set; }
public string Author { get; set; }

public Document( string title, string author )
{
Title = title;
Author = author;
}

public void ChangeDocument(Document newDoc){
this = newDoc;
}
}

 This will cause a compile error with the this keyword as a result.

The code can then be shortened to refactor towards immutability as follows:-

public readonly struct Document
{
public string Title { get; set; }
public string Author { get; set; }

public Document (string title, string author)
{
Title = title;
Author = author;
}
}

 

So in the usage in the code, it can be updated from:-

var doc = new Document();
doc.Title = "SomeTitle";
doc.Author = "SomeAuthor";

to:-

var doc = new Document
{
Title = "SomeTitle",
Author = "SomeAuthor"
}

 

So with this new change, it encourages developers to program with immutability in mind and even though the default parameterless constructor is still available, readonly will cause a compile time error.