How does a generic constraint prevent boxing of a value type with an implicitly implemented interface?

前端 未结 5 1992
南笙
南笙 2020-12-08 12:12

My question is somewhat related to this one: Explicitly implemented interface and generic constraint.

My question, however, is how the compiler enables a ge

5条回答
  •  感情败类
    2020-12-08 12:16

    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.

提交回复
热议问题