user3600372
user3600372

Reputation: 39

boxing unboxing

I found the following code snippet while searching about boxing and unboxing in C#.

class TestBoxing
{
    static void Main()
    {
        int i = 123;

        // Boxing copies the value of i into object o. 
        object o = i;  

        // Change the value of i.
        i = 456;  

        // The change in i does not effect the value stored in o.
        System.Console.WriteLine("The value-type value = {0}", i);
        System.Console.WriteLine("The object-type value = {0}", o);
    }
}
/* Output:
    The value-type value = 456
    The object-type value = 123
*/

Over here it says that even though he value of i changes the value of o remains the same.If so then o is referencing to the value "123" and not i.Is it so?If o stored the value of i then when the value of I was changed the value of o would have changed too. Please correct me if I am wrong.

Upvotes: 1

Views: 2368

Answers (2)

Akhil Jain
Akhil Jain

Reputation: 1

Boxing:- process of converting from value type to reference type For example

int val = 10;
object Obj = val;

UnBoxing:- Its completely opposite to boxing Its the process of converting reference type to value type For example

int val2 = (int)Obj;

Upvotes: 0

Hamid Pourjam
Hamid Pourjam

Reputation: 20754

Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type. When the CLR boxes a value type, it wraps the value inside a System.Object and stores it on the managed heap. Unboxing extracts the value type from the object. Boxing is implicit; unboxing is explicit. The concept of boxing and unboxing underlies the C# unified view of the type system in which a value of any type can be treated as an object.


int i = 123;
// The following line boxes i. 
object o = i;  

enter image description here


o = 123;
i = (int)o;  // unboxing

enter image description here

please read the full article on MSDN.

Upvotes: 8

Related Questions