Home > DeveloperSection > Interviews > Can you tell me about basic concept of boxing and unboxing?

Posted on    September-14-2016 4:42 AM

 C# C# 
Ratings:
 1 Answer(s)
  85  View(s)
Rate this:

Elena Glibart
Elena Glibart

Total Post:6

Points:30
Posted on    September-14-2016 4:42 AM


Boxing is used to store value types into the object type. It is used in the program to store the value of unused variable. We can store the value of the variable with the datatype into object type so that variable can be useful for the rest of the program.

 

Syntax :
int i = 123;
object o = i;
 
Program related to Boxing;
class TBoxing
{
    static void Main()
    {
        int i = 123;
 
 
        object o = i;  // boxing concept
 
                i = 456; 
 
      
        System.Console.WriteLine("The value-type value = {0}", i);
        System.Console.WriteLine("The object-type value = {0}", o);
    }
}
 
Unboxing: Unboxing is used to get the value types from the object type. the datatype must be same for the variable that we have assigned during boxing.
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace ConsoleApplication9
{
    class Program
    {
        static void Main(string[] args)
        {
            int i = 123;
            object o = i; // boxing concept
            i = 456;
            int j = (int)o;//unboxing concept
 
            Console.WriteLine("The value-type value = {0}", i);
            Console.WriteLine("The value-type value = {0}", j);
            Console.ReadLine();
 
        }
    }
}

Modified On Sep-14-2016 04:44:23 AM

Don't want to miss updates? Please click the below button!

Follow MindStick