Dec 13, 2019

BOXING AND UNBOXING

boxing in  c#, unboxing in c#, c# boxing unboxing, c# progarmming, oops boxin gunboxing
boxing un-boxing in c#

Well before the topic let some discussion on value type and reference type.

VALUE TYPE

            “In this type, include all the data type that has its own specific memory allocation in RAM”.
 Such as int, float, char and double. In such a way int cover 2 bytes in memory RAM, float covers 4 bytes space and char have 1 byte. All those data type which have a specific storage in memory is value type. Value type also famous as ‘stack base’.

REFERENCE TYPE

            “This can be a special data type which has no predefined memory space storage in RAM or dynamic memory allocation for this data types”.
But it covers the space accordingly to the given values from the user or programmer. First it accepts values and accordingly to that value it assigns memory space to it. Such types that come into this category are.
a.    Object
b.    Heap
c.    String
Here we considered object only. We also recognize reference type as ‘Heap base’.
             Now when our program need to store size of values more than the allocated memory space or our allocated memory space become greater than need. Then Boxing and Unboxing come into play.

BOXING

            “The mechanism of converting values type to reference type implicitly is called boxing”.
            When our define values type become smaller size then allocated or exceled  the given size then the values type should convert into reference type, thus the process is boxing.

SYNTAX
Valuestype variable = value;
Referencetype variable = value;
Example
int a = 2345;   // values type
object x = a;   // reference type

UNBOXING

            It is the reverse of boxing “the mechanism of converting reference type explicitly to values type is called unboxing”.
            When the predefine reference types have to convert into values type, it only happen when the values cover the size that come to  equal or less then the allocated size of values type such as integer floating point etc.

SYNTAX
Referencetype variable = variable;
Valuestype variable = (datatype) variable;
Example
Suppose the above boxing.
int a = 2345;   // values type
object x = a;   // reference type
int y = (int) x;  // values type

Points to note when unboxing:
        a.    The converting of large value into small amount is called explicit cast.
        b.     When we unboxing then the data types must be declare in that type the values will store like.
int y = (int) x;

0 comments:

Post a Comment

Please do not enter any spam link in the comment box