tags:

views:

61

answers:

1

The best way to explain my problem is with a code snippet:

enum Resource { ..., Size }
class ResourceVector 
{
    int[] values = new int[(int)Resource.Size];

    public static ResourceVector operator + (ResourceVector a, ResourceVector b)
    {...}

    ...
}

We are using this type everywhere as though it were a value type. I.e. we are making the assumption that:

ResourceVector b = a;
b += c;

will not affect a, because that is how we are used to talking about vectors (and that is how a vector with a fixed number of fields does behave, if implemented as a struct).

However since that assumption is wrong, it has led to some extremely subtle bugs.

I am wondering if there is a way to make this behave as a value type, other than just expanding the members of Resource each into their own members in a struct ResourceVector (which requires touching every member of ResourceVector if we wish to add another Resource).

Oh, just in case, we are working with C# 2.0. So no fancy-pants features :-)

Thanks.

+4  A: 

I think you are confusing “value type” with “immutable type”. You actually want your ResourceVector to be an immutable type.

An immutable type is one that has no way to change its contents. Once constructed, an instance retains its value until it is garbage-collected. All operations such as addition return a new instance containing the result instead of modifying an existing instance.

string is the most well-known immutable class. All operations like Substring and Replace return a new string and don’t modify the existing strings.

Once your type is properly immutable, semantically it doesn’t matter so much anymore whether it is a value type or a reference type — but it matters to the performance. If you pass values around a lot, you should probably make it a reference type in order to avoid a lot of unnecessary copying.

Timwi
For some reason I thought that wouldn't work with `+=`. But it turns out it's fine. (This is very embarrassing, as I am a Haskell programmer. *What do you mean immutable?* :-P)
luqui