Thursday, February 3, 2011

Structs - Immutable /Mutable

Structs are value types which more importantly means they are immutable.
Often confused to just containing value types; structs can actually contain reference types e.g. string but the important point is it will contain the values of those reference types.
Structs thus are immutable types.
An interesting example at : http://blogs.msdn.com/b/ericlippert/archive/2008/05/14/mutating-readonly-structs.aspx

It is an error to declare a default (parameterless) constructor for a struct. A default constructor is always provided to initialize the struct members to their default values.
It is an error to initialize an instance field in a struct.

 structures are usually more efficient than classes. You should define a structure, rather than a class, if the type will perform better as a value type than a reference type. Specifically, structure types should meet all of these criteria:
  • Add a note hereRepresents a single value logically.
  • Add a note hereHas an instance size that is less than 16 bytes.
  • Add a note hereIs not frequently changed after creation.
  • Add a note hereIs not cast to a reference type.