Pergunta

Do implicit conversions of types to their base type involve boxing?

Example:

HttpClient client = new HttpClient();
object o = client;
IDisposable d = client;

And if so, is there a performance hit for boxing reference types vs boxing value types?

Foi útil?

Solução

Boxing applies only to value types.

Nothing in your example demonstrates boxing. You've only performed casting of reference types.

From MSDN:

Boxing is the process of converting a value type to the type object or to any interface type implemented by this value type.

Outras dicas

Boxing comprises the process of transfering the data of a value type from the stack to the heap. This is where the performance hit comes from. As the data of reference types is already located on the heap, this process is not relevant for reference types.
Your example shows polymorphism for reference types. This does not involve the process of boxing and is already done when building the project so there is no performance hit at runtime.

You can't box a reference type. It is not possible. Boxing only happens for value types.

If you're putting a value type into a variable of type object, or an interface it implements, then you're boxing. Such conversions will often be implicit, yes.

Boxing / unboxing occurs when you convert a value type to a reference type. If both types are reference types then there is no boxing / unboxing occuring.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top