By 22/07/2015 7 Comments

C# Boxing And Unboxing

  • In C# the object class is a parent/base class of all data types including value types such as int, double, char etc.
  • All data types are derived from Object class implicitly or automatically so the reference of the Object class can refers to any type including value types.
  • When Object class reference variable refers to the value types that process is known as Boxing OR any value type is assigned into the reference variable of Object type and that object can be used like other objects.
  • Because of Boxing the value type is stored inside an object instance and are called the value is Boxed inside an object.
  • The process of Boxing is occurred automatically by C# compiler.
  • Retrieving a value back from the “boxed” object that process is known as Unboxing.
  • The Unboxing process must be performed through an explicit casting.
  • If you will try to unbox an object into different data types the run-time error/exception will be generated.

Example:

using System;
namespace csharpAdvance
{
    class Program
    {
        static void Main(string[] args)
        {
            // Object creation of Object class.
            Object obj = new Object();

            // String value.
            string boxedWebSiteName = "TutorialsTown";

            // String is assigned to object reference, that is “boxing” process.
            obj = boxedWebSiteName;

            // Print “Boxed” value through an object reference.
            Console.WriteLine("Boxed Website Name: {0}", obj);

            // An “Unboxing” process through an explicit casting.
            string unBoxedWebSiteName = (string)obj;

            // Print “Unboxed” value.
            Console.WriteLine("Unboxed Website Name: {0}", unBoxedWebSiteName);
            Console.ReadKey();
        }
    }
    /*  The Output will be:
     
        Boxed Website Name: TutorialsTown
        Unboxed Website Name: TutorialsTown
     */
}





Next Tutorial →



Posted in: C# Advance, C#.NET

Leave your valuable Comment

Have a natural attraction for women cosmetics and replica watches uk clothes, no
more than two for men the most attractive one, is to make their own driving experience, happy and can serve as the facade of the car, another is to highlight the taste edify sentiment rolex replica watch. The replica rolex is undoubtedly the most fashionable accessories, wear a suit to attend the activities, but also get a decent match on the replica watches .