When to use boxing and Unboxing?

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.
Who is Participating?
käµfm³d 👽Commented:
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
Jacques Bourgeois (James Burger)PresidentCommented:
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.
RajG1978Author Commented:
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.
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Jacques Bourgeois (James Burger)PresidentCommented:
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
Jacques Bourgeois (James Burger)PresidentCommented:
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.
käµfm³d 👽Commented:
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.
Jacques Bourgeois (James Burger)PresidentCommented:

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.
käµfm³d 👽Commented:

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.
Jacques Bourgeois (James Burger)PresidentCommented:
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.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.