C# generic – Can I refer to an implement of an interface inside it?

I have some code like this:

public interface Base<TImpl, T1> 
  where TImpl : Base<TImpl, T1> 
{
  public T1 Build(TImpl arg);
}

public class Impl1 : Base<Impl1, int>
{
  public int Value { get; set; }

  public int Build(Impl1 arg)
  {
     return arg.Value;
  }
}

public class Impl2 : Base<Impl2, string>
{
  public string Value { get; set; }

  public string Build(Impl2 arg)
  {
     return arg.Value;
  }
}

The TImpl generic argument seems quite ugly to me. Do I have a chance to safely remove the TImpl part, or remove T1, T2... and can write something like public TImpl.C1 Method(TImpl arg);?

>Solution :

This would be an example of Curiously recurring template pattern. It does not make much sense when there is only one implementing class.

The point of this pattern is to make sure that the argument to Impl.Method is also Impl. There would not be any simple way to avoid this pattern while supplying the same level of type-safety. However, the T2/C2 parameter is never used in the example and could be removed. T1/C1 could be removed if you guarantee that the method always returns an object of some specific type, it is not obvious from this example if this would be the case.

You could always ignore type-safety and just take and return objects, but I would not recommend it.

Leave a Reply