Friday, May 12, 2006

class or struct...

In C# the struct keyword doesn't mean the same thing as in C or C++. First of all functions and properties may be associated with it. Next it's treated as a base type. When I say a base type I refer to int, long etc. These types are copied when sent as arguments instead of a pointer to their location.
This means that struct's are not constructed in the same way as classes and are treated as a base type. This also means that the rules that apply to boxing and unboxing basic types also apply to these types.
From this information we can descern that structs should only be used in extremely rare cases. An example would be a map point or perhaps a complex number structure. This would mean that we have a new type that we wish to be indistinguishable to others, that can be used the same as int or a long.

Any code that contains structs without strong justification of it's usage, along with penalties of using such a construct, shouldn't be allowed to use them. If in any doubt a class should be used instead of a struct.