Search code examples
c#dictionarytupleskey-valuevaluetuple

When TValue of Dictionary<,> is ValueTuple, does it mean that the Value of an item in the dictionary can no longer be modified once intialized?


(.NET 4.8 / C# 7.3)

var test = new Dictionary<string, (int, string)> {
    { "a", (0, "A") }
    , { "b", (1, "B") }
    , { "c", (2, "C") }
};
test["c"].Item1 = 3;

The last line gives me CS1612: Cannot modify the return value of 'Dictionary<string, (int, string)>.this[string]' because it is not a variable.

How do I modify a field in a tuple which is in a Dictionary<,> as an item value?


Solution

  • Just introduce the interim variable:

    var c = test["c"];
    c.Item1 = 3;
    test["c"] = c;
    

    As doc for CS1612 says:

    This error occurs because value types are copied on assignment. When you retrieve a value type from a property or indexer, you are getting a copy of the object, not a reference to the object itself. The copy that is returned is not stored by the property or indexer because they are actually methods, not storage locations (variables). You must store the copy into a variable that you declare before you can modify it.

    For one-liner you can construct a new tuple:

    test["c"] = (3, test["c"].Item2);
    

    Or use record syntax (available since C# 10 - docs):

    test["c"] = test["c"] with { Item1 = 3 };