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("");
}
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/constraints-on-type-parameters
This article lists all the available constraints for generic type parameters. Unfortunately, there seems to be no constraint that does what you need.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With