Solved

When to use boxing and Unboxing?

Posted on 2014-02-05
9
293 Views
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.
0
Comment
Question by:RajG1978
  • 5
  • 3
9 Comments
 
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.
0
 

Author Comment

by:RajG1978
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.
0
 
LVL 40

Assisted Solution

by:Jacques Bourgeois (James Burger)
Jacques Bourgeois (James Burger) earned 250 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);
            Console.WriteLine(val);

            // Output: 45
        }
0
 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 250 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
0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
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.
0
 
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:

http://msdn.microsoft.com/en-us/library/14akc2c7.aspx

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.
0
 
LVL 40
ID: 39839495
@kaufmed

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.
0
 
LVL 75

Expert Comment

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

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.
0
 
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.
0

Featured Post

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Access Web appliction 7 47
asp.net mvc input file 2 32
Vb.net dynamic formulas in runtime 11 61
consuming an asmx web service in winforms application 3 24
This article describes relatively difficult and non-obvious issues that are likely to arise when creating COM class in Visual Studio and deploying it by professional MSI-authoring tools. It is assumed that the reader is already familiar with the cla…
Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
In this video I am going to show you how to back up and restore Office 365 mailboxes using CodeTwo Backup for Office 365. Learn more about the tool used in this video here: http://www.codetwo.com/backup-for-office-365/ (http://www.codetwo.com/ba…
Video by: Mark
This lesson goes over how to construct ordered and unordered lists and how to create hyperlinks.

911 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

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now