Assume I have a struct Point with public int's x and y. I want to change a value and I can. But once I store it in a dictionary, I can no longer do so. Why?
MWE:
using System; using System.Collections.Generic; public class Program { public struct Point { public int x, y; public Point(int p1, int p2) { x = p1; y = p2; } } public static void PrintPoint(Point p) { Console.WriteLine(String.Format("{{x: {0}, y: {1}}}", p.x, p.y)); } public static void Main() { var c = new Point(5, 6); PrintPoint(c); // {x: 5, y: 6} c.x = 4; // this works PrintPoint(c); // {x: 4, y: 6} var d = new Dictionary<string, Point>() { { "a", new Point(10, 20) }, { "b", new Point(30, 40) } }; foreach (Point p in d.Values) { PrintPoint(p); // this works } PrintPoint(d["a"]); // this works // {x: 10, y: 20} Console.WriteLine(d["a"].x.ToString()); // this works // 10 // d["a"].x = 2; // why doesn't this work? } } How come I can access the struct variables when it's in a dictionary but can no longer change them? How do I change them?
d["a"]returns a temporary copy that you aren't storing anywhere. Modifying a temporary wouldn't make sensePointwith the newxvalue and the sameyvalue to the dictionary item:d["a"] = new Point(2, d["a"].y);public Point(int x, int y) { ... }