My question is somewhat related to this one: Explicitly implemented interface and generic constraint.
My question, however, is how the compiler enables a ge
The generic constraint provides only a compile time check that the correct type is being passed into the method. The end result is always that the compiler generates an appropriate method that accepts the runtime type:
public struct Foo : IFoo { }
public void DoSomething(TFoo foo) where TFoo : IFoo
{
// No boxing will occur here because the compiler has generated a
// statically typed DoSomething(Foo foo) method.
}
In this sense, it bypasses the need for boxing of value types, because an explicit method instance is created that accepts that value type directly.
Whereas when a value type is cast to an implemented interface, the instance is a reference type, which is located on the heap. Because we don't take advantage of generics in this sense, we are forcing a cast to an interface (and subsequent boxing) if the runtime type is a value type.
public void DoSomething(IFoo foo)
{
// Boxing occurs here as Foo is cast to a reference type of IFoo.
}
Removal of the generic constraint only stops the compile time checking that your passing the correct type into the method.