ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Boxing, UnBoxing
    C# 2019. 5. 30. 20:44

    *Boxing(박싱)

     

    Boxing is defined to transforming value type to reference type and data which is in Stack is copied to Heap.

     

    In accordance with following example, When interger data int is allocated to object, Boxing automatically occurs.

     

    int i = 123;

     

    object o = i;    //Boxing(implicit transform)

     

    integer data '123' is replicated to Heap which  object o points.

    value type is converted to reference type.Internally,  Value type is converted to System.Object type or interface type that was  implemented by value type.

     

    Unboxing refers to converting reference type to value type. heap data is copied to Stack.

    When converting object o to value type just as following image, Unboxing occurs.

    Unboxing should be done implicitly.

     

     

    caution

    : Unboxing can be done only to the Boxed one.

    Note that not every object can be Unboxed.

    In other words, any Unboxing trial like example below would be failed.

     

    object o = new object();

    int j= (int)o;    //casting exception occurs.

     

    :Unboxing should follow the type that was prior to Boxing.

     

    short i = 123;    //value type

    object o = 1;    //Boxing

    int j = (int)o;    //cannot Unbox to int

    'C#' 카테고리의 다른 글

    C# polymorphism (2/4) - Override  (0) 2019.06.06
    Indexer  (0) 2019.06.06
    C# polymorphism (1/4) - Overloading  (0) 2019.06.05
    Params  (0) 2019.06.04
    Stack , Heap  (0) 2019.06.01
Designed by Tistory.