Tuesday, July 05, 2005

Deploying C:

The Gotcha with Structs and Classes

Here's a piece of code:

my_wee_struct nick = new my_wee_struct(42);
my_wee_struct andy = nick;
andy.s = 4000;
Console.WriteLine('{0}', nick.s);
Console.WriteLine('{0}', andy.s);

If my_wee_struct is a class the output is :
4000
4000

If my_wee_struct is a struct the output is :
42
4000

Note well: Class is a reference type. Struct is an value type. That's the difference!
Boxing

The above discussion on struct and classes leads us to Boxing. The behind your back conversion of a stack item to a heap item.

Bill phases it a bit better: 'Boxing is an implicit conversion of a value type to the type object.'

Take WriteLine:

Console.WriteLine('{0}', nick);

This console method requires the second parameter to be an object. That is an argument that's lurking in the heap, not your stack.

This conversion may an overhead to concerned about - we'll see.

0 Comments:

Post a Comment

<< Home