CAN YOU TELL ME ABOUT BASIC CONCEPT OF BOXING AND UNBOXING?

Elena Glibart

Total Post:19

Points:95
Posted by  Elena Glibart
C# 
C#
 287  View(s)
Ratings:
Rate this:
  1. Elena Glibart

    Post:19

    Points:95
    Can you tell me about basic concept of boxing and unboxing?


    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

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!