Вопрос

Does the following code

string GetString<T>( T? t ) where T : struct
{
  return t.HasValue ? t.Value.ToString() : null;
}

cause boxing, when all Ts it is called with are enums?

This method has the following IL code (first part of method is skipped):

IL_0023:  constrained. !!T
IL_0029:  callvirt   instance string [mscorlib]System.Object::ToString()

I do not see box operation here.

Это было полезно?

Решение

No, it doesn't cause boxing. When the code is compiled the exact type of T is known.

Calling t.Value.ToString() will not cause the value to be boxed, just as calling 42.ToString() will not box the value.

If you call the method with a value that is not nullable, it will be wrapped in a nullable, but that is not a form of boxing because the Nullable<T> type is not an object.

Note that the IL code is not the final code. The code is compiled from IL code to native code by the JIT compiler, and the type of T may not be known until that step.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top