Discuss Boxing and Unboxing in the context of value types and reference types
- By Gurunatha Dogi in C#
- Jul 9th, 2013
- 11799
- 1
About Boxing:
Converting a value type to reference type is called Boxing.
About UnBoxing:
Converting a reference type to value type is called UnBoxing.
Value Types
A data type is a value type if it holds the data within its own memory allocation. Value Types get allocated on stack.
Value Types: Boolean, Char, and Date, SByte, Short, Integer, Long, Byte, UShort, UInteger, or ULong, Struct
Reference Types
A reference type contains a pointer to another memory location that holds the data. Reference Types get allocated on heap.
Reference Types: Class, Objects and All arrays, even if their elements are value types.
With Boxing and Unboxing one can link between value-types and reference-types by allowing any value of a value-type to be converted to any value of a reference-type and vice versa.
Simple Example of Boxing
class Program { static void Main(string[] args) { int A = 5; object B = A;//Boxing } }
As you see in our above code that we have converted value type "int A" with value 5 to reference type "object B" by assigning value type to reference type object.
Simple Example of UnBoxing
class Program { static void Main(string[] args) { int A = 5; object B = A;//Boxing int C = (int)B;// Unboxing } }
As you see in our above code that we have converted reference type "object B" with reference value 5 to value type "Int C" by assigning reference type object to value type.
To check with a valid proof of boxing and unboxing you can check above code i.e. compiled code "dll" or "exe" file using "ILDASM" tool.ILDASM tool which shows half partially compiled code i.e. IL code or Intermediate Language Code.
Please use Visual Studio Command Prompt to launch ILDASM tool
Command: ILDASM and Press Enter Key
Visual Studio Command Prompt : Get in visual studio tools inside your program files.
So this is all about boxing and unboxing if you have any query regarding this topic kindly let me know through your comments. if you like this article share it with your friends.
Gurunatha Dogi
Gurunatha Dogi is a software engineer by profession and founder of Onlinebuff.com, Onlinebuff is a tech blog which covers topics on .NET Fundamentals, Csharp, Asp.Net, PHP, MYSQL, SQL Server and lots more..... read more