Are value types boxed when passed as generic parameters with an interface constraint?
As you figured out already, When a struct
is passed to generic method, It will not be boxed.
Runtime creates new method for every "Type Argument". When you call a generic method with a value type, you're actually calling a dedicated method created for respective value type. So there is no need of boxing.
When calling the interface method which is not directly implemented in your struct type, then boxing will happen. Spec calls this out here:
If thisType is a value type and thisType does not implement method then ptr is dereferenced, boxed, and passed as the 'this' pointer to the callvirt method instruction.
This last case can occur only when method was defined on Object, ValueType, or Enum and not overridden by thisType. In this case, the boxing causes a copy of the original object to be made. However, because none of the methods of Object, ValueType, and Enum modify the state of the object, this fact cannot be detected.
So, as long as you explicitly[1] implement interface member in your struct itself, boxing will not occur.
How, when and where are generic methods made concrete?
1.Not to be confused with Explicit interface implementation. It is to say that your interface method should be implemented in struct itself rather than its base type.