Boxing Unboxing Example in C# – C# Programming Example
General

Boxing Unboxing Example in C#

Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type. When the CLR boxes a value type, it wraps the value inside a System.Object and stores it on the managed heap. Unboxing extracts the value type from the object.

Converting a value type to reference type is called Boxing. Unboxing is the opposite operation and is an explicit operation.

 

Example:

Boxing – Converting a value type to reference type is called boxing. An example is shown below.


Unboxing
 – Converting a reference type to a value typpe is called unboxing. An example is shown below.

 

Example(Structure):

Boxing is used to store value types in the garbage-collected heap. Boxing is an implicit conversion of a value type to the type object or to any interface type implemented by this value type. Boxing a value type allocates an object instance on the heap and copies the value into the new object. Due to this boxing and unboxing can have performance impact.

 

Example(Class):

Will output the value same on the console because the implicit boxing operation that occurs in the assignment of p2 to box causes the value of p to be copied. If had Person instead been declared a class, the value same would be output because p and box would reference the same instance.

 

 

 

 

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: