structure in a Dictionary, not modifiable?

G

Glenn

Hi,

I was able to specify a structure for a Dictionary, but once I tried
to modify it, I get an error specifying that I cannot modify the
return value because it's not a return value..?

I can always do an array of the struct, just wanted to be able to
access via the name instead of looping thru to find the index.

TIA
Glenn
 
M

Marc Gravell

The compiler is stopping you from making an easy mistake: because it
is value-type, as soon as you get the value you have a *private* copy
(on the stack) - hence modifying the value would achieve nothing. If
your struct is mutable (editable), then you can get a copy into a
local variable, update that variable, and then set the modified value
back into the dictionary (note that this may break any iterators that
are in use at the time).

However! My general advice is to keep structs immutable (readonly). If
you need to make changes to properties, then in most cases it sounds
like you should actually be using a class instead.

Marc
 
G

Glenn

The compiler is stopping you from making an easy mistake: because it
is value-type, as soon as you get the value you have a *private* copy
(on the stack) - hence modifying the value would achieve nothing. If
your struct is mutable (editable), then you can get a copy into a
local variable, update that variable, and then set the modified value
back into the dictionary (note that this may break any iterators that
are in use at the time).

However! My general advice is to keep structs immutable (readonly). If
you need to make changes to properties, then in most cases it sounds
like you should actually be using a class instead.

Marc

Marc,

Was wondering if the copy scenario was viable.. but sounds like it not
a good practice. OK, class instead then.

Thanks for the quick reply :)
Glenn
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top