Object - Boxing

Boxing is the process of converting a value type into the type object.
This wraps the value inside the System.Object and stores it on the managed heap Boxing is implicit
Forcing value types to act as reference types

int value5 = 23; 
object object1 = value5;

UnBoxing extracts the value type from the object Unboxing is explicit


object object2 = 54; 
int value6 = (int)object2;


Converting a value type into a reference type is called boxing.


Converting a reference type into a value type is called UnBoxing
The value is "boxed" inside an object and then subsequently "unboxed" back to its value type


Boxing is implicit when you provide a value type and a reference type is expected.
This is an implicit conversion of a value type to a reference type
Boxing a value allocates an instance of an Object and copies the value into the new object instance.
The compiler can detect that you have submitted a value type and silently boxes it within an Object.
You can explicitely cast the value type is you want to.


Explicit

int MyNumber; 
object MyObject;
   MyObject = MyNumber;
   MyObject.ToString();

Implicit

int MyNumber; 
   MyNumber.ToString();



© 2023 Better Solutions Limited. All Rights Reserved. © 2023 Better Solutions Limited TopPrevNext