Solved

When to use boxing and Unboxing?

Posted on 2014-02-05
9
285 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

Expert Comment

by:Jacques Bourgeois (James Burger)
Comment Utility
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
Comment Utility
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
Comment Utility
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 74

Accepted Solution

by:
käµfm³d   👽 earned 250 total points
Comment Utility
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
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 
LVL 40

Expert Comment

by:Jacques Bourgeois (James Burger)
Comment Utility
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 74

Expert Comment

by:käµfm³d 👽
Comment Utility
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

Expert Comment

by:Jacques Bourgeois (James Burger)
Comment Utility
@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 74

Expert Comment

by:käµfm³d 👽
Comment Utility
@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

Expert Comment

by:Jacques Bourgeois (James Burger)
Comment Utility
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

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Using MS Code on my Mac 6 44
asp.net bundle 8 32
work allocation; web development; vba; access; 4 46
Showdialog 8 20
Recently while returning home from work my wife (another .NET developer) was murmuring something. On further poking she said that she has been assigned a task where she has to serialize and deserialize objects and she is afraid of serialization. Wha…
In my previous article (http://www.experts-exchange.com/Programming/Languages/.NET/.NET_Framework_3.x/A_4362-Serialization-in-NET-1.html) we saw the basics of serialization and how types/objects can be serialized to Binary format. In this blog we wi…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

763 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

13 Experts available now in Live!

Get 1:1 Help Now