Re: Boxing and Unboxing ??
- From: "Jesse McGrew" <jmcgrew@xxxxxxxxx>
- Date: 12 Jan 2007 18:29:24 -0800
Peter Olcott wrote:
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 memory, (such as an integer) and a reference type
is simply the address of this data.
It seems that .NET has made at least one of these two terms mean something
entirely different. can someone please give me a quick overview of what the
terms "value type" and "reference type" actually mean in terms of their
underlying architecture?
Well, if you're familiar with Delphi or Java, you've already seen
reference types. Class instances in those languages are always stored
as pointers to data on the heap, just like reference types in .NET, and
when you access an object's fields, you're implicitly deferencing the
pointer. In Delphi, records are equivalent to value types; in Java,
primitives like int and double are.
A value type is a type that's normally passed by value, and whose
contents *can* (but don't have to) live on the stack. A reference type
is always passed by reference, and always lives on the heap. A variable
of a value type takes up the entire size of the type, and assigning one
such variable to another copies the contents; a variable of a reference
type only takes up the size of a pointer, and assigning one to another
simply makes both variables point to the same data.
Boxing means copying a value type onto the heap, along with some type
information, so that it can be used like any other instance of
System.Object. This is because even though all types in .NET derive
from System.Object (a reference type), value types are stored
differently. To keep polymorphism and garbage collection working, the
data has to be copied at runtime, because you can't just use a pointer
to a value type on the stack as a managed reference - for example, you
might store that pointer in a global variable, where it would have to
live on after the function returns and its stack frame is destroyed.
Unboxing is the reverse - copying the contents of a boxed value type
(from the heap) back onto the stack so you can work with it in its
usual form.
Jesse
.
- Follow-Ups:
- Re: Boxing and Unboxing ??
- From: Jon Skeet [C# MVP]
- Re: Boxing and Unboxing ??
- From: Peter Olcott
- Re: Boxing and Unboxing ??
- References:
- Boxing and Unboxing ??
- From: Peter Olcott
- Boxing and Unboxing ??
- Prev by Date: RE: Newb Question....Database Entry Form
- Next by Date: Re: Boxing and Unboxing ??
- Previous by thread: Re: Boxing and Unboxing ??
- Next by thread: Re: Boxing and Unboxing ??
- Index(es):
Relevant Pages
|
Loading