Monday, May 2, 2016

Boxing

Boxing is a process of converting a value type to the object type or to any other interface type which is implemented by this value type. When CLR boxes a value type it wraps the value inside a System.Object and stores it on the managed heap. Boxing is done implicitly. It is used to store the value types in the garbage collected heap. It allocates an object instance on the heap and copies the value into the new object. For example:
using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
  
namespace ConsoleApplication1  
{  
    class boxing  
    {  
public static int a
        {  
            get;  
            set;  
        }  
        public static void Main ( )  
        {   
            int i = 10;   
            object j = i;   //statement for boxing
  
            Console.WriteLine ("Enter the value: ", a);  
            a= Convert.ToInt32 (Console.ReadLine ( ));  
  
            if (i <= a)  
            {  
                i += a;  
                Console.WriteLine ("\n The sum is: ", i);  
            }  
            else  
            {  
                Console.WriteLine ("\nWrong answer…");  
            }  
            Console.ReadLine ( );  
        }    
    }    
} 

No comments: