Learn Boxing and Unboxing in C#.

Posted by in C# category on for Beginner level | Points: 250 | Views : 3950 red flag

In this C# article will learn the concepts of Boxing and Unboxing step by step.

Boxing and Unboxing are the concepts which are deals with value types and reference type. While internally value types and reference type refers to stack and heap memory type. In short if we go to learn Boxing and Unboxing then knowing internals of it becomes mandatory. So before moving ahead we will quickly understand one liner for each of them.

Stack Memory :- It stores normal data type of .NET like int, bool, double, float, var etc.

Heap Memory :- It stores classes and object. Object references are stored on stack while actual objects are stored on heap.

Value type:- It creates two separate copies on memory location for different variables assigned same values. With that if value of one variable is changed then value of other value is not changed.

Reference type :- Under this, reference is initially stored on stack and actual value stored on heap. So if different objects are assigned with same values then reference will actually point to value stored on heap.

Hope above short explanation is clear which will help in understanding the concept of boxing and unboxing.

Boxing :- Moving value from data type “int” to “object” is moving value from Stack to Heap changing from value type to reference and it is called as Boxing.

Unboxing :- And when value of “object” stored on heap it can be moved to data type “int b” and it will store “int” value on Stack memory and this is termed as Unboxing.

Please Note : While we write programming code ensure to avoid boxing and unboxing which leads to performance degrading of the application program. But it is equivalently true to avoid in some scenario doing boxing to unboxing or unboxing to boxing.

Internals of Boxing and Unboxing code

Below is the snapshot of visual studio which shows practical code of boxing and unboxing where first we have declared variable “a” with data type as “int” and value of variable as “789”.

Then declare an object “obja” and set it to “a” in other words we are doing moving from value type to reference type which is called as boxing.

Third statement is setting object “obja” to new variable “int b” which is moving reference type to value type and it is called as unboxing.

You can also see internal of boxing and unboxing by using ILDASM tool for that open developer command prompt using Visual Studio tool. Once the command prompt window is open write “ILDASM” and press enter which will open “IL ASM” window.

On “IL ASM” window is open under it, double click on the Main() method under Manifest as shown in the image down below.

You will see boxing and unboxing source code internally written in MSIL code.

Now as we have seen MSIL code under ILDASM next we will practically prove that doing boxing i.e. moving “int” to “object” type in a program affects the performance as compare to “int” to “int” type.

Performance comparison

In order to prove performance implication using boxing and unboxing code. In this part we use below code where we have boxing code where we are moving “int” data type to “object”

private void Box()
            int a = 789;
            object b = a;

And with this will do comparison with normal assigning value sample(non-boxing) where we will move value of “int” data type to “int” data type.

private void AssignValue()
            int a = 789;
            int b = a;

Comparison will be done using stopwatch and can be used by importing class “System.Diagnostic” which will show timing in millisecond to execute each code. With the help of time taken to execute each boxing and normal assigning value code we can easily compare it.

So the minimum time taken to execute the code will be winner for that we will use windows form on that we will drag and drop from Tool box two buttons. Now on each button write the “For Loop” code which will run 10000 times and out of that one button will run boxing code while the other will run non-boxing method “For Loop” for 10000 times. Time taken by each method to run “For Loop” will be measured by stopwatch.

private void button1_Click(object sender, EventArgs e)
            Stopwatch stpwaobj = new Stopwatch();
            for (int a = 0; a < 10000; a++)
            stpwaobj.Stop(); ;
            label1.Text = stpwaobj.Elapsed.ToString();

To write “For Loop” to run boxing code do a double click on first button which will go its code behind click event. On the code behind write code for boxing which run the boxing method. Similarly on the second button by double clicking it write code for non-boxing.

private void button2_Click(object sender, EventArgs e)
            Stopwatch stpwaobj = new Stopwatch();
            for (int a = 0; a < 10000; a++)
            label2.Text = stpwaobj.Elapsed.ToString();

Finally to display output from stopwatch values we will use label. Execution time taken to run each method will be displayed on label and each has label to be associated with each button.

Now that you have understood the code and working of it. Next we will Build its solution which will check for code writing error if found any will have to correct it and if found successful then run the windows application which will show “Form1” named windows front which is shown as below.

If you now click on “Boxing” button it will show the reading taken on label next to “Boxing” button. Similarly if you click on “Assigning Variable” which runs non-boxing method internally will shows its execution time value on label.

Down below on the image you will see time taken for executing time for both the methods. With screen results it is clear and proves that “Boxing” method takes more time which is “2589 ms” compare to “Non-Boxing” method which takes “1167 ms”.

Hope that all of the above fundamental explanation and practical executed shown is clear by the reader.

Below is one fine video for newbie to C# programming a must recommendation for fresher. Do view it if you are a fresher or want to brush up from scratch you will surely like this starter video of the C# 100 hrs series: -

Page copy protected against web site content infringement by Copyscape

About the Author

Full Name: Ahtesham Shaikh
Member Level: Bronze
Member Status: Member
Member Since: 10/3/2016 2:36:04 AM
Country: India
Ahtesham Shaikh
Hey Friends, Myself Ahtesham a coder, writer & technical supporter for IT world and for my company Questpond. Having 10+ years of experience in microsoft technologies like WCF, WPF, MVC, Sharepoint, AngularJS, MSBI, Excel 2000 - 2013, Powerpoint, C#, SQL Server and so on. I just find myself happy and satisfy by doing this job. Apart from profession love reading novels and other digital network books. I'm a faculty at Questpond and do take trainings on c#, object oriented programming, msbi, sharepoint, mvc, mvc, angularJS and so on. Feel free get in touch me for one-to-one trainings, offline trainings @Andheri Mumbai, Online training via microsoft live meeting.

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)