Search code examples
c#genericsinheritancetype-parameter

C# - Specifying type parameters of super-class in sub-classes?


I am trying to do the following in C#.

public class Parent<T> where T : Parent<???>
{
  public T Prop { get; set; }
}

public class Child : Parent<Child>
{
}

How can I do it?


Solution

  • This works fine:

    public class Parent<T> where T : Parent<T>
    {
      public T Prop { get; set; }
    }
    
    public class Child : Parent<Child>
    {
    }
    

    Do be careful with this as c# does not enforce a true Parent/Child relationship. For example, given the above code, it is also legal for me to then do this:

    public class Stranger : Parent<Child>
    {
    }
    

    If you write unit tests then it's worth writing a type checker that looks for this mispattern.