Wednesday, 31 January 2007

Boxing & Unboxing

Boxing is the conversion of a value type to a reference type, and unboxing converts a reference type to a value type. This is best avoided for intensively repetitive tasks such as within foreach statements. The following tips are useful for avoiding uncessary boxing:
  • Implement type-specific versions (overloads) for procedures that accept various value types. It is better practice to create several overloaded procedures than one that accepts an Object argument.
  • Use generics whenever possible instead of accepting Object arguments.
  • Override the ToString, Equals, and GetHash virtual members when defining structures.

No comments: