473,699 Members | 2,153 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Boxing and Unboxing of Value-Types when passed to a method call

Hi All,
First of all I think this is gonna be one of those threads :-) since I have
bunch of questions which make this very controversial:-0)
Ok,Let's see:

I was reading an article that When you pass a Value-Type to method call
,Boxing and Unboxing would happen,Consider the following snippet:
int a=1355;
myMethod(a);
......
void myMethod(int b);

Can somebody describes what exactly happens in the stack and (probably in
the heap) when this code is executed?

Thanks for your time in advance,I will ask my other questions as we go
further with this thread.

Cheers,
Raza Alirezaei


Nov 16 '05 #1
24 2613
I was reading an article that When you pass a Value-Type to method call
,Boxing and Unboxing would happen,Consider the following snippet:
int a=1355;
myMethod(a);
.....
void myMethod(int b);

There's no boxing going on here. It would only happen if the parameter
type was object, or an interface implemented by the argument.


Mattias

--
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/ | http://www.dotnetinterop.com
Please reply only to the newsgroup.
Nov 16 '05 #2
> int a=1355;
myMethod(a);
.....
void myMethod(int b);
In the above case no boxing is done cuz you are passing int to int. Boxing
is done when value types are converted to ref types.
Moreover, value types are allocated on stack, ref types are allocated on
heap.

Ab.
http://joehacker.blogspot.com
"ALI-R" <ne****@microso ft.com> wrote in message
news:uf******** ******@TK2MSFTN GP12.phx.gbl... Hi All,
First of all I think this is gonna be one of those threads :-) since I
have
bunch of questions which make this very controversial:-0)
Ok,Let's see:

I was reading an article that When you pass a Value-Type to method call
,Boxing and Unboxing would happen,Consider the following snippet:
int a=1355;
myMethod(a);
.....
void myMethod(int b);

Can somebody describes what exactly happens in the stack and (probably in
the heap) when this code is executed?

Thanks for your time in advance,I will ask my other questions as we go
further with this thread.

Cheers,
Raza Alirezaei

Nov 16 '05 #3
Ok,Let's change it in this way:

int a=1355;
myMethod(a);
.....
void myMethod(Object b);
Now ,boxing and unboxing is happned or not?

Cheers,
Reza Alirezaei

"Abubakar" <em**********@y ahoo.com> wrote in message
news:OZ******** ******@TK2MSFTN GP14.phx.gbl...
int a=1355;
myMethod(a);
.....
void myMethod(int b);


In the above case no boxing is done cuz you are passing int to int. Boxing
is done when value types are converted to ref types.
Moreover, value types are allocated on stack, ref types are allocated on
heap.

Ab.
http://joehacker.blogspot.com
"ALI-R" <ne****@microso ft.com> wrote in message
news:uf******** ******@TK2MSFTN GP12.phx.gbl...
Hi All,
First of all I think this is gonna be one of those threads :-) since I
have
bunch of questions which make this very controversial:-0)
Ok,Let's see:

I was reading an article that When you pass a Value-Type to method call
,Boxing and Unboxing would happen,Consider the following snippet:
int a=1355;
myMethod(a);
.....
void myMethod(int b);

Can somebody describes what exactly happens in the stack and (probably in the heap) when this code is executed?

Thanks for your time in advance,I will ask my other questions as we go
further with this thread.

Cheers,
Raza Alirezaei


Nov 16 '05 #4
KH
Boxing is the process of treating a value type as a reference type. See:
http://msdn.microsoft.com/library/de...nversionpg.asp

object obj = Int32.MaxValue; // The int value is "boxed" to a reference type
int i = (int)obj; // The int held by obj is "unboxed" with the cast

I of course don't know how boxing is actually implemented in the CLR, but
one possibility I suppose is that a temporary class is created with a member
of the value type, and its reference (pointer) can then be passed around as
with any other reference type.

Of note is that the boxed value does not point at the original value, as:

//////////////////////////////////////////////////

struct T
{
public int Value; // default = 0
};

class C
{
static void Main()
{
T t = new T();
object obj = t;

t.Value += 1;

Console.WriteLi ne("Original value = {0}", t.Value);
Console.WriteLi ne("Object value = {0}", ((T)obj).Value) ;
}
};

//////////////////////////////////////////////////

This code prints:

Original value = 1
Object value = 0

If the boxed object pointed at the original value then the object's value
would also be 1.

- KH
"ALI-R" wrote:
Hi All,
First of all I think this is gonna be one of those threads :-) since I have
bunch of questions which make this very controversial:-0)
Ok,Let's see:

I was reading an article that When you pass a Value-Type to method call
,Boxing and Unboxing would happen,Consider the following snippet:
int a=1355;
myMethod(a);
......
void myMethod(int b);

Can somebody describes what exactly happens in the stack and (probably in
the heap) when this code is executed?

Thanks for your time in advance,I will ask my other questions as we go
further with this thread.

Cheers,
Raza Alirezaei


Nov 16 '05 #5
straight out of the reference. watch for line wrap.

http://msdn.microsoft.com/library/de...nversionpg.asp

"ALI-R" wrote:
Ok,Let's change it in this way:

int a=1355;
myMethod(a);
.....
void myMethod(Object b);
Now ,boxing and unboxing is happned or not?

Cheers,
Reza Alirezaei

"Abubakar" <em**********@y ahoo.com> wrote in message
news:OZ******** ******@TK2MSFTN GP14.phx.gbl...
int a=1355;
myMethod(a);
.....
void myMethod(int b);


In the above case no boxing is done cuz you are passing int to int. Boxing
is done when value types are converted to ref types.
Moreover, value types are allocated on stack, ref types are allocated on
heap.

Ab.
http://joehacker.blogspot.com
"ALI-R" <ne****@microso ft.com> wrote in message
news:uf******** ******@TK2MSFTN GP12.phx.gbl...
Hi All,
First of all I think this is gonna be one of those threads :-) since I
have
bunch of questions which make this very controversial:-0)
Ok,Let's see:

I was reading an article that When you pass a Value-Type to method call
,Boxing and Unboxing would happen,Consider the following snippet:
int a=1355;
myMethod(a);
.....
void myMethod(int b);

Can somebody describes what exactly happens in the stack and (probably in the heap) when this code is executed?

Thanks for your time in advance,I will ask my other questions as we go
further with this thread.

Cheers,
Raza Alirezaei



Nov 16 '05 #6
Mattias is correct. Here are some more details. In your code snippet:

int a=1355;
myMethod(a);
......
void myMethod(int b)
{ ... }

What would happen in C# is the same thing that would happen in any
other language: the compiled program will place a 32-bit integer on the
stack and invoke myMethod(). No boxing. No unboxing. However, consider
the following example:

int a = 1355;
myMethod(a);
....
void myMethod(object o)
{ ... }

In this case, myMethod is expecting an object, which is a reference
type, not a value type. For a reference type, the method is expecting a
pointer on the stack, or in C# parlance, a _reference_ to an object.
So, the myMethod(a) call would do the following:

o "Box" the value of a: create an Int32() value on the heap and
initialize it to 1355.
o Call myMethod with a reference to the new Int32() object.

The call _has_ to do this in order to pass a consistent argument to
myMethod(). In other words, myMethod() has to know what it's receiving,
and since a reference to an instance on the heap is the "lowest common
denominator," the compiled program "boxes" (allocates an object on the
heap for) the value type being passed in. This _doesn't_ happen in your
code snippet because both the caller and the method agree that what's
being passed is always an int, never anything else, so there's no need
to reduce it to an object.

As well, consider the following snippet:

int a = 1355;
myMethod(a);
....
void myMethod(ICompa rable o)
{ ... }

This time, IComparable is an interface, not a class, but the effect is
the same: since IComparable things can be value or reference types, and
so to pass a consistent thing to myMethod(), the running program boxes
the integer and passes it as a reference to an Int32 object instance.

Note that all of this is more important when considering the collection
structures provided by the .NET framework. Before V2.0 and generics
comes along, if you put a bunch of integers in an ArrayList (or a
Hashtable, or a SortedList, or a...) then all of the integers (or
doubles, or booleans, or ...) will be boxed before they're put into the
ArrayList. They have to be, because an ArrayList is defined as being a
collection of _objects_, and so is designed to hold object references,
not hold value types like integers directly.

This is where _unboxing_ comes in: when you place an integer in an
ArrayList, it must be made into an object instance reference, and so
space is allocated on the heap, and a pointer to that space is placed
in the ArrayList ("boxing"). When you ask to retrieve an integer from
the ArrayList:

int a = (int)myArrayLis t[i];

your compiled program follows the object reference stored at
myArrayList[i], fetches the value from within the object on the heap,
and assigns that value to a (unboxing).

Much of the need for boxing and unboxing goes away with the
introduction of generics in V2.0, but that's fodder for another post.

Nov 16 '05 #7
Abubakar <em**********@y ahoo.com> wrote:

<snip>
Moreover, value types are allocated on stack, ref types are allocated on
heap.


That's an incorrect oversimplificat ion.

See http://www.pobox.com/~skeet/csharp/memory.html

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #8
Thanks for your nice replies ,specifically the one for Bruce wood.
I got what I wanted from the First question.I'm going to summorize it and
move on the second question:

Again cosidering my snippet:
int a=1355;
myMethod(a);
.....
void myMethod(Object b);
Here is what happens,tell me if I am wrong:
"b" (Reference to the boxed "a" which is on the heap) is created on the
stack and it points to boxed "a" object on the heap.Infact what we have on
the heap is only a shallow copy of original "a" with the same data but
completely different thing(as we can change the value of original "a" and
nothing would happen to Boxed "a" object on the heap).

ok ,Moving on.I'd like to change my code a bit more:
int a=1355;
myMethod(ref a);
.....
void myMethod(ref int b);


I assume that there is no boxing and unboxing invovled here ,but I'd like to
know the space allocation on stack and heap for this guy.

More changes in the next thread,
Thanks for monitoring this thread.

Reza Alirezaei

I'd like to change the snippet a bit to add my second question:

"ALI-R" <ne****@microso ft.com> wrote in message
news:uf******** ******@TK2MSFTN GP12.phx.gbl... Hi All,
First of all I think this is gonna be one of those threads :-) since I have bunch of questions which make this very controversial:-0)
Ok,Let's see:

I was reading an article that When you pass a Value-Type to method call
,Boxing and Unboxing would happen,Consider the following snippet:
int a=1355;
myMethod(a);
.....
void myMethod(int b);

Can somebody describes what exactly happens in the stack and (probably in
the heap) when this code is executed?

Thanks for your time in advance,I will ask my other questions as we go
further with this thread.

Cheers,
Raza Alirezaei

Nov 16 '05 #9
"Mattias Sjögren" wrote:
There's no boxing going on here. It would only happen if the parameter
type was object, or an interface implemented by the argument.


Also ValueType, although I can't think of any reason why you'd want to do
that ;-)
Nov 16 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
1415
by: emma middlebrook | last post by:
Hi Is this class and code snippet not good enough to see the differences between having a collection of a value type compared with having a collection of references to a reference type (containing that same value type)? Using a wrapper around Win32's QueryPerformanceCounter and some tracing I see very little difference. class WrappedRectangleF {
3
1796
by: Steve | last post by:
Hi, I have a class like: public ClassA { int vals1; int vals2; }
16
1622
by: Ed A | last post by:
Hi all: I'm using a struct of type Point that is being passed on to a method as a refrence type (boxing), the UpdatePoint method changes the coordinates of this point as such: Point p = new Point(); UpdatePoint( P ); .. ..
10
1241
by: Nathan Neitzke | last post by:
I am writing an app that might largely benefit from using a struct instead of a class. However, it needs to be rich enough where there are methods available. My question is - every time you call a method on a struct, is it boxed? Because that would be a huge perf hit. I am assuming that it does have to be boxed, but if anyone knows for sure that would be great!
5
1310
by: Mike Labosh | last post by:
Can someone provide a link to something a bit more useful than the MSDN topics? -- Peace & happy computing, Mike Labosh, MCSD "Musha ring dum a doo dum a da!" -- James Hetfield
4
2973
by: Peter Olcott | last post by:
I want to be able to make my .NET applications run just as fast as unmanaged C++. From my currently somewhat limited understanding of the .NET framework and the C# language, it seems that Boxing/Unboxing might present of problem. Since C++ has pointer syntax, I was thinking that this might eliminate the need for Boxing and Unboxing. Am I right? One of the things that my application needs is something exactly like std::vector<unsigned...
5
1754
by: Joe | last post by:
Consider the following code loop: for(int x = 0; x < 100; x++) { string sLoop = "Loop # " + (x+1).ToString(); Console.WriteLine(x); } I was told that the (x+1).ToString() was a boxing statement, and would therefore cause a memory leak because there's no explicit unboxing
94
5668
by: Peter Olcott | last post by:
How can I create an ArrayList in the older version of .NET that does not require the expensive Boxing and UnBoxing operations? In my case it will be an ArrayList of structures of ordinal types. Thanks.
19
13717
by: ahjiang | last post by:
hi there,, what is the real advantage of boxing and unboxing operations in csharp? tried looking ard the internet but couldnt find any articles on it. appreciate any help
161
7828
by: Peter Olcott | last post by:
According to Troelsen in "C# and the .NET Platform" "Boxing can be formally defined as the process of explicitly converting a value type into a corresponding reference type." I think that my biggest problem with this process is that the terms "value type" and "reference type" mean something entirely different than what they mean on every other platform in every other language. Normally a value type is the actual data itself stored in...
0
9055
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8944
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8899
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7786
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6550
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5889
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4391
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4638
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3075
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.