Select Page

When using variables in C# you need to be aware of and careful with boxing and unboxing. For example the following code;

int discount = 20;
object discPerc = discount;
discount = 15;

int discPercent = (int)discPerc;

In this instance the value of discount is 15 but the value of the implicitly converted discPerc and the explicitly cast discPercent are still 20.

This is because when converting from a value type to a reference type a copy of the value is taken not a reference to the value.

Given that the move from the Value type to the Reference type was implicit you could wind up with an ugly little bug.

%d bloggers like this: