articles

Home / DeveloperSection / Articles / Boxing and Unboxing

Boxing and Unboxing

Trusartta Kumar Mahanta1172 11-Aug-2019

What is the Difference Between Boxing and Unboxing?

Boxing and Unboxing is one of the most Important Concept in C#.

In Boxing and Unboxing Contain three Data Types

1-Value Type(int,char etc)

2-Reference Type(object)

3-Pointer Type()

Boxing

-Basically, value type to reference(object) type of Conversion is called Boxing.

-Boxing is Implicit type Conversion Process.

-Here Value Stored in the Stack Memory and reference(object) Copied Stored on the Heap Memory.

   Ex- int x=100;

   Object obj=x; //---Boxing

Ex-using System;

public class Test{

 static public void Main()

 {

  int val = 2020;

  // Boxing

  object o = val;

  // Change the value of val

  val = 9437;

  Console.WriteLine("Value type of val is {0}", val);

  Console.WriteLine("Object type of val is {0}", o);

 }

--------------------------------------------------------------------------------------------------------------

Unboxing

Unboxing is Convert Reference type into value Type is Called Unboxing. This is the Wrong Concept.

Correct Ans-

If a value type which is converted into reference type is converted back to value type ,we call it as Unboxing, but while Performing unboxing Explicit Conversion is Required.

-Unboxing is Explicit type Conversion.

-In Unboxing the object stored on the Heap memory Copied stored on the Stack Memory.

     Ex-

Value Type----------------Reference Type--------------Value Type

  Int y=Convert.ToInt32(obj); ----------------Unboxing

Ex:

using System;

public class Test {

 static public void Main()

 {

  int val = 2020;

  // Boxing

  object o = val;

  // Unboxing

  int x = (int)o;

  Console.WriteLine("Value of o is {0}", o);

  Console.WriteLine("Value of x is {0}", x);

 }

Note: A Direct reference type can never be Converted to Value Type.


Updated 11-Aug-2019
I am a passionate programmer and a Software Engineer love blogging and Developing applications using Microsoft Technologies and Other Advance Web Technology.

Leave Comment

Comments

Liked By