Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

generics

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("");
}
like image 521
Jan Avatar asked Dec 03 '25 10:12

Jan


1 Answers

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.

like image 60
Rudey Avatar answered Dec 04 '25 23:12

Rudey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!