There are cases when an instance of a value type needs to be treated as an instance of a reference type. For situations like this, a value
The code
int x = 42;
Console.Writeline("The value of x is {0}", x );
actually boxes and unboxes because Writeline
does an int
cast inside. To avoid this you could do
int x = 42;
Console.Writeline("The value of x is {0}", x.ToString());
Beware of subtle bugs!
You can declare your own value types by declaring your own type as struct
. Imagine you declare a struct
with lots of properties and then put some instances inside an ArrayList
. This boxes them of course. Now reference one through the []
operator, casting it to the type and set a property. You just set a property on a copy. The one in the ArrayList
is still unmodified.
For this reason, value types must always be immutable, i.e. make all member variables readonly
so that they can only be set in the constructor and do not have any mutable types as members.