modify dictionary value

  • Thread starter Thread starter Jon Slaughter
  • Start date Start date
J

Jon Slaughter

How do I modify the value of a dictionary object?

I have something like

Dictionary<string, A> Q = ...

Where A is a struct.

I want to change some values in A but

Q["somestr"].x = 1;

doesn't work because it makes them read only.

If I do something like

A a = Q["somestr"];

a.x = 1;

then of course it doesn't update the value in the dictionary.

The only way I know to do it is remove the key and then re-add it with the
new value... but surely there is a better way?
 
Jon Slaughter said:
How do I modify the value of a dictionary object?

I have something like

Dictionary<string, A> Q = ...

Where A is a struct.

I want to change some values in A but

Q["somestr"].x = 1;

doesn't work because it makes them read only.

If I do something like

A a = Q["somestr"];

a.x = 1;

then of course it doesn't update the value in the dictionary.

The only way I know to do it is remove the key and then re-add it with the
new value... but surely there is a better way?

No - or at least not without a bit of jiggery-pokery with interfaces.
But then it's a bad idea to make the struct mutable in the first place.
This is just one of the places where mutable structs are painful. Avoid
them, avoid them, avoid them.
 
Jon Skeet said:
Jon Slaughter said:
How do I modify the value of a dictionary object?

I have something like

Dictionary<string, A> Q = ...

Where A is a struct.

I want to change some values in A but

Q["somestr"].x = 1;

doesn't work because it makes them read only.

If I do something like

A a = Q["somestr"];

a.x = 1;

then of course it doesn't update the value in the dictionary.

The only way I know to do it is remove the key and then re-add it with
the
new value... but surely there is a better way?

No - or at least not without a bit of jiggery-pokery with interfaces.
But then it's a bad idea to make the struct mutable in the first place.
This is just one of the places where mutable structs are painful. Avoid
them, avoid them, avoid them.

I moved on to a keyed collection. Thats actually what I originally wanted
but didn't know it existed. (a little easier than using a dictionary because
my value was a struct in the first place).

I changed the struct to a class though so I can easily modify the values.

Thanks,
Jon
 
Back
Top