BOXING AND UNBOXING

Today in Engineer's World, we are discussing a very important topic of C# - Boxing and Unboxing in very easy way. Posted By- +Manish Kumar Gautam +LIVE VIAR +ASP.NET SOLUTIONS

Click imaginationhunt.blogspot to see latest Blogs
 

Welcome friends, the Blog is to explain Boxing and Unboxing. Confusing and useless terms for beginner's and even for some professional too.



In C# how can we convert one type to another? The first idea that comes to your mind is by using implicit or explicit conversion and type casting. But can we convert a value of one type into a value of another type? Can we? Answer is yes.

The process of converting a value type to a reference type is called boxing. The inverse process, converting a reference type to a value type, is called unboxing. This is illustrated in the following code:

int i = 58959; // a value type  
object o = i; // boxing  
int j = (int)o; // unboxing

What is object? And why object is so much important in box and unbox? object (Go to Definition) is derive from Object class. It supports all classes in .Net Framework class hierarchy and provides low-level class hierarchy to derived classes. This is the ultimate base class for all classes it the .Net Framework; it is the root of the type hierarchy.

Boxing:
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.

Rules of Boxing:
-> No need to tell the compiler that you are boxing from value to reference. Because compiler take care of it. It is implicit.
using System;

namespace AspnetSolutions
{
    class Boxing
    {
        public static void Main()
        {
            DateTime presentdate1 = DateTime.Now;  //Part1
            object obj1 = presentdate1;  //You can directly pass (Implicitly)
            Console.WriteLine(obj1);


            char name = 'A';  //Part2
            object obj2 = name;
            Console.WriteLine(obj2);

            int number = 25;  //Part3
            object obj3 = number;
            Console.WriteLine(obj3);
        }
    }
}

  
Output:
The output is very straight forward. 
In Part 1 we are taking the DateTime.
In Part 2 we are taking the character (char). 
In Part 3 we are taking the integer. 



UnBoxing:
Unboxing is used to store reference type in stack. Unboxing is an explicit conversion of reference type to the value type.



Rules of Unboxing:
1. We can only unbox a value that has previously been boxed.

using System;

namespace AspnetSolutions
{
    class Unboxing
    {
        public static void Main()
        {
            try
            {
                int i = 25;
                object o = i;

                long l = (long)o;
                Console.WriteLine("i: " + i);
                Console.WriteLine("o: " + o);
                Console.WriteLine("l: " + l);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}


Output:
We get error Message- Specified Cast is not valid (InvalidCastException). Because we have intialized variable i as integer and during unbox we explicit want our variable to long data type. 
 


2. Before unboxing C# checks that value type we request is actually stored in the object under conversion, only then the value is unboxed.
3. Unboxing copies the value out of the object. It doesn't manipulate the value.

using System;

namespace AspnetSolutions
{
    class free
    {
        public static void Main()
        {
            int i = 25;
            Console.WriteLine("Initial value of i = " + i);
            object o = i;
            i = (int)o;  //Unboxing

            Console.WriteLine("Value of o = " + o);
            Console.WriteLine("After Unboxing the value of i = " + i);
        }
    }
}


Output:
You can notice that just before Unboxing the value of o is 25 and after that value is same for i = 25. Means it copies the value out of the object.




To read STRING in C# (Declaration and Initialization) PART-1 - Click here.

Related Questions:-

#newtoprgm try first program

Q-1 Choose correct type of variable scope for given defined variables.

 class ABC
  {
      static int m;
      int n;
      void fun (int x , ref int y, out int z, int[] a)
      {
         int j = 10;
      }
  }

Scope declaration:
 

A) m = static variable, n = local variable, x = output parameter, y = reference parameter, j = instance variable, z =output parameter, a[0]= array element
 

B) m = static variable, n = instance variable, x = value parameter, y = reference parameter, j = local variable, z =output parameter , a[0] = array element
 

C) m = static variable, n = instance variable, x = reference parameter, y = value parameter, j = local variable, z =output parameter, a[0] = array element
 

D) m = local variable, n = instance variable, x = reference parameter, y = value parameter, j = static variable, z =output parameter, a[0] = array element  

Ans- Option(B)
Explanation- By definition of scope of variables.

Q-2 Correct output for following set of code is:

    public static void Main(string[] args)
    {
        int i = 123;
        object o = i;
        i = 456;
        System. Console. WriteLine("The value-type value = {0}", i);
        System. Console. WriteLine("The object-type value = {0}", o);
        Console. ReadLine();
    }

A) 123, 123
B) 456, 123
C) 456, 456
D) 123, 456


Ans- Option(B).
Explanation-
The concept of boxing is implemented here. The variable ‘i’ of ‘int’ type is boxed using variable ‘o’ of object type and hence value stored inside it is initialized to the object variable ‘o’. In Next, variable ‘i’ is again initialized with some value overriding its previous stored value.
Output-
456, 123


Click imaginationhunt.blogspot to see latest Blogs

Q-3 Correct output for following set of code is:

  public static void Main(string[] args)
  {
      int i = 546;
      object o = i;
      int n =(int) o;
      o = 70;
      System. Console. WriteLine("The value-type value = {0}", n);
      System. Console. WriteLine("The object-type value = {0}", o);
      Console. ReadLine();
  }

A) 546, 0
B) 546, 546
C) 546, 70
D) 70, 546

Ans- Option(C).
Explanation-
The concept of ‘unboxing’ is implemented here. To ‘unbox’ an object back to value type, we should have to do it explicitly as “int n = (int) o”.
Output-
546, 70


Keep learning and sharing!!!

Comments

Popular posts from this blog

SSC CGL 2016 Tier-1 Marks / Result

DATA TYPES IN C#

Pattern printing program

IS STRING MUTABLE OR IMMUTABLE IN .NET?

Top Mutual Funds

SSC CGL 2017 TIER 2 RESULT OUT

JUST IN TIME (JIT)

Can we have multiple Main methods in one class

TOP 15 VISUAL STUDIO SHORTCUT KEYS

Top 10 Interview Tips and Questions