Thursday, October 22, 2020

Boxing and unboxing in c#.



In c# there are two type of datas .one is value type and other is reference types.

Variables of different data types

string stringVar = "Hello";

int intVar = 500;

float floatVar = 20.2f;

char charVar = 'E';

bool boolVar = true;

 

value types include simple types such as int,float,double, Boolean or enum, struct types.

Reference type includes  class,array,interface, delegate and array.

Boxing means converting from value type to reference type.

Unboxing means converting from reference  type to value type.

Boxing:

  1. class Test  
  2. {  
  3.     static void Main()  
  4.     {  
  5.         int i = 1;  
  6.         object o = i; // boxing  
  7.         int j = (int)o; // unboxing  
  8.     }  
  9. }  

 

In the above example 1 is assigned to value type variable  i.

This I value is assigned to reference type o.

This is called boxing.

Object o is type casted into type int and then assigned to value type int named j.

This is unboxing.

Note when we do boxing we directly assign the value while in unboxing there is an explicit type cast is required.

 

 

 


No comments:

Post a Comment