Wednesday, January 02, 2008

Considerations while designing own types

Though Value Types are created on stack and in some situation gives better performance as compare to Reference Types, we should not tempt with choosing Value Type for every situation. General misconception is that if we are not having complex functionality, we should choose Value Type. We should not forget that size of instance also does matter in copy operation. In functions, Value Types are passed by copying the instance as a parameter. Similarly if function is returning Value Type, that is also copied in caller function's memory space. We can make our type as Value Type in following situations:

  1. Type has no members that modify any of the type's instance field. In other words, type is immutable.
  2. Type should not lie in inheritance chain. That means, it should inherit from any other type and also any other type should derived from it.
  3. Instances of the type are small in size (16-20 bytes or less)
  4. Instances of the type are large (greater than 20 bytes) and are not passed as argument or return value in functions.

No comments: