Struct strikes back

Guriy Samarin
2 min readAug 29, 2021

Should you use the structure-type property in .NET? I’m not sure I ever did. But some time ago I was asked to help with code like this:

public class TestClass
{
public StructField StructField { get; set; }
}

public struct StructField
{
public string PropertyString { get; set; }
public int PropertyInt { get; set; }
}

public static class SomeClass
{
public static unsafe void TestMethod()
{
TestClass test = new();

test.StructField.PropertyString = "";
test.StructField.PropertyInt = 0;

test.StructField = default;
}
}

Can you guess the problem?

test.StructField.PropertyString = "";
test.StructField.PropertyInt = 0;

The problem is accessing not the actual struct property (its backing field), but a copy of it (test.StructField — getter and getter copy value type), so you will get no chance to change the underlying field. Obviously making StructField solves this problem.

The main idea is to avoid mutable structs. It is not functional style architectural recommendation — like you should try to use only immutable types (because of benefits they bring). It is no-no for almost any .NET types design ideas you can have.

This issue is addressed in Microsoft Type Design Guidelines — DO NOT define mutable value types (for example from guidelines: when a property getter returns a value type, the caller receives a copy. Because the copy is created implicitly, developers might not be aware that they are mutating the copy, and not the original value). If you want to check out more struct property examples and advanced comments — you can visit the StackOverflow links below.

Reference

--

--

Guriy Samarin

Software developer at Amazon. Web (mostly backend) development now. My stack — .NET (APS.NET Core MVC).