Microsoft has the following rules for using struct:
Consider defining a structure instead of a class if instances of the
type are small and commonly short-lived or are commonly embedded in
other objects.Do not define a structure unless the type has all of the following characteristics:
- It logically represents a single value, similar to primitive types (integer, double, and so on).
- It has an instance size smaller than 16 bytes.
- It is immutable.
- It will not have to be boxed frequently.
As far as I understand, you create struct when you want a value-type behavior. Of course this gives you copying overhead when assigning and passing it to functions. But why would you follow #2 and #3? What if your value type is just too large? Moreover, I don’t understand why you would ever make an immutable type to be a value type. If the type is immutable, you would better save time for passing it by reference, since anyway it cannot be changed.
The reason that I’m asking is that I’m making a game, where objects have properties like Coordinates, Velocity etc. of the type Vector2d. The question is, should I make Vector2d immutable struct (wouldn’t that require tons of additional memory?), mutable struct (people say they are evil) or just class (I will have to always call vector.Clone() because otherwise I may unintentionally get two objects having same vector variable)
The
inttype is an immutable type and is a perfect example of why you need immutable value types.Imagine if
intwere a reference type. It would be very expensive if you had to dereference every time you used an integer. This is in fact what happens when you use “boxed” integers (e.g. integers that are stored in a variable of typeobject). One of the improvements in .NET compared to Java is that collections can hold unboxed integers.Yes if it’s large and immutable then you would save time by passing it by reference. That is why the guidelines suggest that large types should be reference types.