Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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 };
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading