Re: Boxing and Unboxing ??
- From: "Bruce Wood" <brucewood@xxxxxxxxxx>
- Date: 13 Jan 2007 10:17:48 -0800
So a member function can not add two integer members without unboxing them
first? That would sound like horrendous design.
No. _Only_ if you declare the integer as being of type "object". Viz:
public class SimpleClass
{
private int a;
private int b;
public SimpleClass(int first, int second)
{
this.a = first;
this.b = second;
}
public int Sum()
{
return this.a + this.b;
}
}
No boxing, no unboxing. The integers are stored on the heap with the
object's state, and used directly in the sum operation.
Versus:
public class SimpleClass
{
private object a;
private object b;
public SimpleClass(int first, int second)
{
this.a = first; // Causes boxing
this.b = second; // Causes boxing
}
public int Sum()
{
return (int)this.a + (int)this.b; // "int" cast causes
unboxing
}
}
In the first case, the integers are value types, stored just as they
would be in C++. In the second case, they are declared as reference
types, so the CLR allocates space for them on the heap and copies the
values "first" and "second" into the boxes on the heap. The object
state then maintains references to the two boxes. In order to use the
values, you must fetch them from the boxes on the heap, or "unbox" them
(which, in reality, is just a pointer dereference, which is probably
what you would expect anyway).
.
- Follow-Ups:
- Re: Boxing and Unboxing ??
- From: Peter Olcott
- Re: Boxing and Unboxing ??
- References:
- Boxing and Unboxing ??
- From: Peter Olcott
- Re: Boxing and Unboxing ??
- From: Jesse McGrew
- Re: Boxing and Unboxing ??
- From: Peter Olcott
- Re: Boxing and Unboxing ??
- From: Jesse McGrew
- Re: Boxing and Unboxing ??
- From: Peter Olcott
- Re: Boxing and Unboxing ??
- From: Barry Kelly
- Re: Boxing and Unboxing ??
- From: Peter Olcott
- Boxing and Unboxing ??
- Prev by Date: Re: Boxing and Unboxing ??
- Next by Date: Re: Is it possible to hide methods to certain classes?
- Previous by thread: Re: Boxing and Unboxing ??
- Next by thread: Re: Boxing and Unboxing ??
- Index(es):
Relevant Pages
|
Loading