tabs

Friday, November 1, 2013

Boxing and UnBoxing in c# with Examples

In order to understand what Boxing and Un-Boxing are, initially one need to understand what are Value Types and Reference Types.. Boxing and Un-Boxing are just the technical terms to typecast either value types to reference types or reference types to value types.

Boxing

Converting value type to reference type is called as Boxing.
Example:
 int x = 100;
 Object obj = i;
Here ‘x’ is of type int which is a value type which is taken as reference by an object ‘o’ which is a reference type.

UnBoxing

Converting a Reference type to a value type is known as UnBoxing.
Example:
Object obj = 100;
int i = (int)obj
Here just the reverse happened, object type is type-casted to integer, so its UnBoxing.


Perfomance:

  • Value Types will be accessed faster compared to Reference Types as they have their value directly in their own memory allocation.
  • Reference Types will be accessed a bit slower compared to the Value Types because they it has to refer another memory location to get the value which costs one more transaction.
  • But it is always recommended not to use Boxing and UnBoxing everywhere except the situation demands. Because these operations cost some additional time to execute and may show impact on the overall performance of your program if used frequently.

No comments:

Post a Comment