Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win


When to use boxing and Unboxing?

Posted on 2014-02-05
Medium Priority
Last Modified: 2014-02-06
I know the definition for Boxing and Unboxing. I want to know when I can actual use them.
Can anyone give me a small example where They can be used in real world.
Question by:RajG1978
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 3
LVL 40
ID: 39837179
They are not used very often, except by programmers that come from a background (such as VB classic) where paramaters are passed by reference by default.

One good example is the TryParse method, that you find in all the basic value types (Integer, Double, Date).

If it had been defined, as is most often the case. in such a way that you pass a value by value (no boxing) and it returned a Boolean telling you if a conversion is possible or not, you would need a second command to actually perform the cast from the value to a String.

By letting you pass the value as a reference (which involves boxing and unboxing), it enables you to perform 2 operations with only one command. Perform the cast and tell you if it worked or not. Since TryParse is very often used to validate data input, you save a lot of code by having both operations done with only one call.

Author Comment

ID: 39837279
sorry I am confused. Let  us take below code
string text1 = "x";
	int num1;
	bool res = int.TryParse(text1, out num1);

Open in new window

Can this be boxing and unboxing example, if so can explain it in detail.
LVL 40

Assisted Solution

by:Jacques Bourgeois (James Burger)
Jacques Bourgeois (James Burger) earned 1000 total points
ID: 39837320
No, not at all.

You begin all your questions with "I know the definition for this and that", but you do not seem to grasp the concepts at all.

The following is an example of boxing and unboxing. The ref before the parameters forces boxing and unboxing. It is done automatically in the background because it passes a value object (int) by reference (ref).

       static void Method(ref int i)
            // Rest the mouse pointer over i to verify that it is an int.
            // The following statement would cause a compiler error if i
            // were boxed as an object.
            i = i + 44;

        static void Main()
            int val = 1;
            Method(ref val);

            // Output: 45
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

LVL 75

Accepted Solution

käµfm³d   👽 earned 1000 total points
ID: 39837957
They are not used very often, except by programmers that come from a background
That statement is misleading. .NET programmers use boxing and unboxing all the time. Whenever you assign a value type to a reference type, you are using boxing; when you do the reverse, you are unboxing. Boxing happens implicitly most of the time, which is why programmers don't tend to think about it much. Unboxing is never implicit. An explicit instance of boxing would be something like:

object o = 32;  // 32 is an integer (type), so it gets boxed into a reference type to make the assignment work

Open in new window

Unboxing would be the opposite:

int i = (int)o;

Open in new window

An example of implicit boxing would be:

ArrayList a = new ArrayList();

a.Add(32);  // since an ArrayList holds items of type object, the int is boxed into a reference type before it is added

Open in new window

Unfortunately, what JamesBurger shows above is neither boxing nor unboxing. It is passing by reference.

More information:  http://msdn.microsoft.com/en-us/library/yz2be5wk.aspx
LVL 40
ID: 39838041
Boxing and unboxing occur implicitely when you pass a value object by reference, so my example does use the concept.

I say that boxing is not used very often, because there are few reasons to treat a value object, such as an Integer, through an Object variable. Usually, you know if a variable will be an Integer, a Double or a Date, and there is no need to treat it as an object.

Object variables are mostly used for reference objects, and reference objects do not implicate boxing.
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 39838800
Boxing and unboxing occur implicitely when you pass a value object by reference
No, they don't. Boxing and unboxing have nothing to do with passing by reference. Passing by reference is the difference between passing the actual value of a variable versus an address to where that variable's data is located. Read the documentation:


There is no boxing of a value type when it is passed by reference.

there are few reasons to treat a value object, such as an Integer, through an Object variable. Usually, you know if a variable will be an Integer, a Double or a Date, and there is no need to treat it as an object.
Agree, to a point. We as .NET programmers don't often treat integers as object explicitly, but implicitly--as in my ArrayList example--happens more often than most developers realize.

and reference objects do not implicate boxing.
No, not in the general sense, but as in my first example, the assignment of the variable type to the reference type (in this case object) does imply boxing.
LVL 40
ID: 39839495

I owe you a big one for that last post. Still learning things after all that time.

When .NET came out in 2002, there were numerous articles about VB optimization or about differences between VB6 and VB.NET that talked about the penality of passing value objects ByRef, "because of the boxing involved", and gave tricks to minimize the impact. I still have an old book that says that.

I am always sceptic when I read something that does not come from the official documentation, but it came out so often that I took it as a fact. Seems that everyone was repeating the error the first one did. Similar to all these examples we still see where they create a DataSet to handle only one DataTable. Mistakes have an old habit of being repeated over and over again in this age were everybody can talk to the whole world.

That little note that you extracted from the documentation started to appear only in 2008. I never saw it. One stops reading about some topics in the documentation when he is working with its 5th version of Visual Studio.

I humbly bow in dishonor as a samurai in front of his master after doing (or saying) a very wrong thing.

I apologize to anybody whom I might have confused with my erroneous statements.
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 39839554

I started working with .NET under Visual Studio 2005, which was .NET 2.0. I have never worked with .NET 1.x, so maybe things were different back then.
LVL 40
ID: 39839634
I doubt that something so basic would change, but the Common Language Runtime moved from version 1.0/1.1 to 2.0 with Visual Studio 2005 (the CLR version did follow the Framework version in these early days). So it might be.

But I carefully review the What's New in every version of Visual Studio, and it seems to me that a change like that would have been mentioned and would have attracted my attention.

Now, if an historian is listening and is looking for a research project into .NET history...

I was probably simply fooled by a series of erroneous articles. .NET was so new and so huge that a lot of these where written in the beginning... and still are. My posts at the beginning of this thread are probably already forever recorded in the search engines of this world, and would have added to that series of bad post if you had not come forward to correct me.

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
In this video, Percona Solution Engineer Rick Golba discuss how (and why) you implement high availability in a database environment. To discuss how Percona Consulting can help with your design and architecture needs for your database and infrastr…
Are you ready to place your question in front of subject-matter experts for more timely responses? With the release of Priority Question, Premium Members, Team Accounts and Qualified Experts can now identify the emergent level of their issue, signal…

610 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question