The problem is that
Coordinates
is a
struct
- so it's a value type, and that means that what is returned by
dict["A"]
is not a variable - it's a copy of the value of a variable, and can't be directly altered because it's not a
lvalue
You can store the result in a variable and change that:
Coordinates c = dict["A"];
c.y = 666;
but as this is a value type, that will not modify the dictionary in any way.
Probably the best way is to change your
struct
to a
class
:
static void Main(string[] args)
{
CoordinatesDictionary dict = new CoordinatesDictionary();
dict.Add("A", 1, 10, 100);
dict.Add("B", 2, 20, 200);
dict.Add("C", 3, 30, 300);
dict["A"].Y = 666;
}
public class Coordinates
{
public int X { get; set; }
public int Y { get; set; }
public int Z { get; set; }
}
public class CoordinatesDictionary : Dictionary<string, Coordinates>
{
public void Add(string key, int x, int y, int y)
{
this.Add(key, new Coordinates() { X = x, Y = y, Z = z });
}
}
Since your
Coordinates
will be stored in a Dictionary, the
struct
would need to be boxed anyway, and a class may well be more efficient as a result.
This may help (even if it doesn't mention Dictionaries!):
Using struct and class - what's that all about?[
^]