Evil Code #005 : Readonly Value Types

Time to review another of Evil Code Series and this time, we are dealing with read-only value types. Review the below code and predict the output.


struct DummyStruct
    public int MyValue {get; set;}
    public int Increment() => ++MyValue;
    public DummyStruct(int myValue)=> MyValue = myValue;
public class DemoClass
    private readonly DummyStruct _readOnlyStruct;
    public DemoClass() => _readOnlyStruct = new DummyStruct(2);
    public void IncrementAndDisplayValue() => Console.WriteLine($"({_readOnlyStruct.Increment()},{_readOnlyStruct.MyValue})");
var myClass = new DemoClass();


Strangely enough, the output is {3,2}. Yes, it means the Increment Method return a value of 3 for MyValue, but a follow-up statement to display MyValue explicitly, ends up with a value 2. Isn’t that bizarre ? Well not quite if one think a bit deeper.

Being a value type, whenever we are accessing it, we only get a copy of the value. The original _readOnlyStruct.MyValue is immutable and doesn’t change. But, the copy isn’t quite immutable and gets altered, which is returned by the Increment method. And when you are calling the _readOnlyStruct.MyValue property in the later part of program, another copy of the immutable value type is created which has the original value. This is the reason we are seeing the output. A more detailed explanation has been provided by Eric Lippert in his blog .
Happy Coding !!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s