Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top