C# Puzzles – Puzzle #3: Mutable Structs

Photo by Tyler Quiring

Every C# developer knows there are classes and structs, and at least once in an interview was asked about boxing. Additionally, they understand the concepts of mutable and immutable. This is where this puzzle will focus today.

Note: Scroll selectively to not spoil the results.

Lets jump into it.

class Program
{
    static void Main(string[] args)
    {
        var c = new Counter();
        var d = new Dictionary<string, Counter>();

        d["hello"] = c;
        c.Increment();

        Console.WriteLine(c.Count);
        Console.WriteLine(d["hello"].Count);

        d["hello"].Increment();

        Console.WriteLine(c.Count);
        Console.WriteLine(d["hello"].Count);

        Console.ReadLine();
    }
}

public class Counter
{
    public int Count { get; private set; }

    public void Increment()
    {
        Count += 1;
    }
}

We have a class with an int property. A method that increments it. In the function we are putting an instance of it into a dictionary, and the incrementing it both from the variable and from the dictionary indexer.

What do you expect the output to be?







Space to avoid spoilers.






1 1 2 2 – Nothing unexpected, but you know what is next…

class Program
{
    static void Main(string[] args)
    {
        var c = new Counter();
        var d = new Dictionary<string, Counter>();

        d["hello"] = c;
        c.Increment();

        Console.WriteLine(c.Count);
        Console.WriteLine(d["hello"].Count);

        d["hello"].Increment();

        Console.WriteLine(c.Count);
        Console.WriteLine(d["hello"].Count);

        Console.ReadLine();
    }
}

public struct Counter
{
    public int Count { get; private set; }

    public void Increment()
    {
        Count += 1;
    }
}

Let’s change Counter to a struct. What do you expect to happen now?







Space to avoid spoilers.






1 0 1 0 – Well if I didn’t give it away in the beginning to you why does this happen?

The dictionary is storing the values by value not by reference for structs. This means the increment on the variable will only effect that instance. The dictionary has the previous referenced value. Then calling increment from the dictionary’s index has no effect.

This is a very basic understand you should have before ever using a struct. It is fundamental, but difficult to understand at first.

I must thank Eric Lippert for this example, as it comes from his stack-overflow answer on the topic.

Photo by Amarnath Tade

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

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

Facebook photo

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

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: