Boxing and unboxing are important concepts in C#.
Jun 10, 2015 02:00 0 Comments C# (C-Sharp) SOUNDARYA

Boxing Vs Unboxing in C#

Boxing and unboxing are important concepts in C#. C# Type System contains three data types: Value Types (int, char, etc.)Reference Types (object) and Pointer Types.

Basically, boxing and unboxing deals in converting a Value Type to a Reference Type, and vice versa.

 

BOXING

UNBOXING

It converts value type into an object type.

It converts an object type into value type.

Boxing is an implicit conversion process.

Unboxing is the explicit conversion process.

Here, the value stored on the stack is copied to the object stored on the heap memory.

Here, the object stored on the heap memory is copied to the value stored on the stack .

Example:

// C# program to illustrate Boxing

using System;

  

public class Program {

    static public void Main()

    {

        int val = 2019;

  

        // Boxing

        object o = val;

  

        // Change the value of val

        val = 2000;

  

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

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

    }

}

 

 

Output:

Value type of val is 2000

Object type of val is 2019

Example:

// C# program to illustrate Unboxing

using System;

  

public class Program {

    static public void Main()

    {

        int val = 2019;

  

        // 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);

    }

}

 

 

Output:

Value of o is 2019

Value of x is 2019

 

Prev Next
About the Author
Topic Replies (0)
Leave a Reply
Guest User

You might also like

Not sure what course is right for you?

Choose the right course for you.
Get the help of our experts and find a course that best suits your needs.


Let`s Connect