How to ensure that class derived from abstract generic class uses itself as generic parameter

Viewed 72

I have an abstract class:

public abstract class MyAbstractBase<T> : INotifyPropertyChanged where T : MyAbstractBase<T> {}

where I derive a couple of classes:

public class Concrete1 : MyAbstractBase<Concrete1> {};
public class Concrete2 : MyAbstractBase<Concrete2> {};

is there a way to constraint MyAbstractBase so that the the generic type is that of the specific concrete type?

So this should produce a compiler error:

public class Concrete1 : MyAbstractBase<Concrete2> {};

My current workaround is a check in the base constructor which doesn't throw a compiler warning unfortunately.

protected MyAbstractBase()
{
    _ = this as T ?? throw new Exception("");
}
1 Answers
Related