Jon Skeet [C# MVP] wrote:
There's more to it than that.
Consider the case where you do:
object Return5()
{
int x = 5;
return x;
}
If it just returned a pointer to the original stack value then:
a) How would it know what type the value was meant to be?
Well, it'd have to store that information somewhere, of course. Maybe
you'd just change the language so that all stack frames include type
information for all variables in the frame, and the pointer wouldn't be
just to the variable data, but to that typed information describing the
variable data.
Alternatively, you could wrap the reference for the stack variable in
some sort of container. We could call it, oh...I don't know...a
"package"? No, too long. How about "carton". No, reminds me of
cigarettes. Maybe the word "box" would work?
:)
b) What happens after the stack is popped at return time?
Oh, I know! You just capture the variable, the way anonymous delegates
work. :)
My biggest issue with the idea of referencing the original variable is
that it means that the value could change externally to the boxed value,
and that change would be reflected in the user of the boxed type. This
is contrary to the normal behavior of value types. IMHO, one main point
of boxing is to wrap the value in something that can be used as a
reference type, but which retains the normal behavior of a value type.
If you just refer to the original value, which is available for changing
by other code elsewhere, then the boxed value type doesn't work like a
value type any more.
Pete