C# in Depth

Cover of C# in Depth
Order now (3rd edition)

Modifying the results of an indexer

Chapter 3: Parameterized typing with generics: 3.2.1

Created: 1/28/2008
Last updated: 1/28/2008

In listing 3.1, I include the following line of code:

frequencies[word]++;

I mention that this may seem odd at first. There are situations where similar code could produce incorrect results - in particular, if you try to change a field or property on a value type which is returned from a dictionary, the compiler will complain. For example (C# 3 code just to be more concise):

using System.Collections.Generic;

struct MutableStruct
{
    public int value;
}

class Test
{
    static void Main()
    {
        var map = new Dictionary<string,MutableStruct>();
        
        map["hello"] = new MutableStruct();
        map["hello"].value++;
    }
}

This gives a compiler error of:

Test.cs(15,9): error CS1612: Cannot modify the return value of 'System.Collections.Generic.Dictionary.this[string] ' because it is not a variable

Of course, I'm sure you wouldn't use a mutable struct anyway, would you?