Boxing:
Converting a value type to reference type is called Boxing.
Unboxing:
Unboxing is an explicit operation. You have to tell which value type you want to extract from the object.
Int32 vt= 10; //value type variable
object rt= vt; /*memory is allocated on the heap of size equal to size of vt,the value type bits are copied to the newly allocated memory and the address of the object is returned and stored in rt.This is basically called Boxing.*/
Int32 vt2=(Int32)rt;//Unboxing
Purpose of Boxing and UnBoxing :
.NET provides a unified type system. All types including value types derive from the type object. It is possible to call object methods on any value, even values of primitive types such as int.
private void display()
{
Console.WriteLine(3.ToString());
}
calls the object-defined ToString method on an integer value.In programs that need int values to behave like objects, this capability is available on demand. This ability to treat value types as objects bridges the gap between value types and reference types that exists in most languages.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment