Re: Boxing and Unboxing of Value-Types when passed to a method call
From: Bruce Wood (brucewood_at_canada.com)
Date: 01/24/05
- Next message: Nicole Schenk: "Re: How to evaluate in C# a string of expression"
- Previous message: MuZZy: "Re: How do you make one dotnet exe talk to another dornet.exe like a dotnet dll?"
- In reply to: ALI-R: "Re: Boxing and Unboxing of Value-Types when passed to a method call"
- Next in thread: ALI-R: "Re: Boxing and Unboxing of Value-Types when passed to a method call"
- Reply: ALI-R: "Re: Boxing and Unboxing of Value-Types when passed to a method call"
- Messages sorted by: [ date ] [ thread ]
Date: 24 Jan 2005 15:42:18 -0800
Yes, that is my understanding.
After all, all method arguments _must_ be allocated on the stack,
whether they are references to items on the heap, references to other
items on the stack, or values being passed directly. So, by definition
"b" _must_ be on the stack.
However, we also know that "b" is a direct reference to the memory
location called "a" that is holding the value 1355, which, because it's
a local variable, is also on the stack.
Therefore, the argument to myMethod, b, is a reference held on the
stack that refers to another stack location called "a" that holds the
int value. The heap is not involved at all in this case.
If, on the other hand, a method argument is a reference _type_ (as
opposed to a reference _parameter_: read Jon Skeet's excellent article
to clear up any confusion between the two) and you pass a value, thus
requiring boxing, the compiler must create a temporary object to hold
the value (it must "box" the value), and in so doing you might think
that it has two options: it could create the temporary object in the
heap and pass a reference to that to the method, or you might imagine
it could create the temporary object on the stack, if it (the compiler)
could know that the boxed value will be thrown away immediately as the
method returns.
However, the compiler can't know that, because the method (for example
ArrayList.Add) might take that object reference and copy it somewhere
(such as in an ArrayList data structure), and so deallocating the
temporary, boxed copy upon return would be disastrous.
For this reason boxes for value types are always created in the heap:
the compiler never knows if you're going to grab a copy of the
reference and store it somewhere, so it defers the deallocation problem
to the garbage collector.
- Next message: Nicole Schenk: "Re: How to evaluate in C# a string of expression"
- Previous message: MuZZy: "Re: How do you make one dotnet exe talk to another dornet.exe like a dotnet dll?"
- In reply to: ALI-R: "Re: Boxing and Unboxing of Value-Types when passed to a method call"
- Next in thread: ALI-R: "Re: Boxing and Unboxing of Value-Types when passed to a method call"
- Reply: ALI-R: "Re: Boxing and Unboxing of Value-Types when passed to a method call"
- Messages sorted by: [ date ] [ thread ]
Relevant Pages
|