Boxing / Unboxing

S

Steve

Hi,

I have a class like:

public ClassA
{
int[] vals1;
int[] vals2;
}


Many instances of ClassA are created and stored in a Hashtable.

Does the following statement cause any boxing/unboxing to be
undertaken (z is an instance of ClassA):

z.vals[0]=z.vals[1]+z.vals[2];


Also:

int i = z.Vals[0]; // This would cause unboxing?

double d = (double)z.Vals[0]; // Is this the same as the previous
statement or would it incur extra penalties casting the value to a
double?



thanks
 
N

Nicholas Paldino [.NET/C# MVP]

Steve,

No, there is no boxing or unboxing. Basically, the array is of type
int, so no boxing/unboxing needs to take place when setting or getting a
value from it.

Hope this helps.
 
N

Niki Estner

Steve said:
Hi,

I have a class like:

public ClassA
{
int[] vals1;
int[] vals2;
}


Many instances of ClassA are created and stored in a Hashtable.

Does the following statement cause any boxing/unboxing to be
undertaken (z is an instance of ClassA):

z.vals[0]=z.vals[1]+z.vals[2];

No, boxing only occurs when you convert a value type (like an integer) to a
reference type (like System.Object).
Also:

int i = z.Vals[0]; // This would cause unboxing?

no; this line takes an integer out of the int[] array and assigns it to a
local variable.
There would be unboxing if Vals was an object[] array, or a collection class
like ArrayList (which contains objects).
double d = (double)z.Vals[0]; // Is this the same as the previous
statement or would it incur extra penalties casting the value to a
double?

Yes and no: again, there is no boxing/unboxing penalty. But of course
converting a 32-bit integer to a 64-bit floating point variable does take
time and (never forget this) may also cost precision!

Niki
 
S

Steve Hearne

int i = z.Vals[0];

So this statement would simple cause the value in the array to be copied
over from the Heap to the stack.

And the statement:

z.Vals[0] = i;

would cause the reverse?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top