C# and structs
23 July 2007 12:58[I don't know of anyone that reads this that will care. But maybe it will prove useful to someone.]
As I've just spent a while being bitten by this, I thought I'd pass this hard-won information along:
In C#, structs are passed by value, not reference (even though they act in many respects like classes).
An example, taken from all-too-real life, in which this becomes a problem:
Suppose that you have a dictionary in which you're keeping structs that contain statistics, stored in fields. Periodically, you retrieve a struct from this dictionary and update one of its statistics. However, since structs are passed by value, however, the struct that you modify is not the same as the one that the dictionary owns, and so the dictionary's struct's statistics are never modified.
That is to say: AAAAAAAARGH! (I mean, seriously: I realize that C# has a lot of adherents that came directly from C/C++, and those languages do the same thing. But why would you _want_ to pass a struct by value? All that stuff dumped on the stack...and structs can be _huge_.)
As I've just spent a while being bitten by this, I thought I'd pass this hard-won information along:
In C#, structs are passed by value, not reference (even though they act in many respects like classes).
An example, taken from all-too-real life, in which this becomes a problem:
Suppose that you have a dictionary in which you're keeping structs that contain statistics, stored in fields. Periodically, you retrieve a struct from this dictionary and update one of its statistics. However, since structs are passed by value, however, the struct that you modify is not the same as the one that the dictionary owns, and so the dictionary's struct's statistics are never modified.
That is to say: AAAAAAAARGH! (I mean, seriously: I realize that C# has a lot of adherents that came directly from C/C++, and those languages do the same thing. But why would you _want_ to pass a struct by value? All that stuff dumped on the stack...and structs can be _huge_.)