The best way to avoid boxing of value types is: just use them as values!
I think you have completely misread that reference. What it says is that using ref
parameters does not cause boxing. It does not say that it is a way to avoid
boxing.
Boxing happens when a value type is used in a reference context, such as being cast to an Object. This article says that passing parameters by reference must not be confused with the concept of reference types, but confuse them seems to be exactly what you've done.
Summary by 280Z28:
In other words, avoid the following two operations:
- Casting or assigning the value to a variable of type
object
(or passing the value as an argument for a method parameter of type object
).
- Casting or assigning the value to a variable which is an interface type (such as
IEnumerable
), or passing the value as an argument for a method parameter which is an interface type.
There are exceptions to this rule (e.g. calling some generic methods), and there are cases where boxing can occur in other contexts, but these are the primary situations to be aware of when you are trying to avoid unnecessary boxing of value types.