Suppose I have an abstract base class that I want to declare members in that will match the type of the classes that derive from this base class.
public abstract class BaseClass
{
protected BaseClass parent;
}
public class DerivedClass1 : BaseClass
{
// parent could be of type DerivedClass2
}
public class DerivedClass2 : BaseClass
{
// parent could be of type DerivedClass1
}
This won't work because the parent
field in each derived class can be anything that derives from BaseClass
. I want to ensure that the parent
field in DerivedClass1
can only be of type DerivedClass1
. So I'm thinking maybe I should use generics.
public abstract class BaseClass<T> where T : BaseClass<T>
{
protected T parent;
}
This may seem confusing and circular, but it does compile. It's basically saying parent
is of type T
which has to derive from the generic BaseClass
. So now a derived class can look like this:
public class DerivedClass : BaseClass<DerivedClass>
{
// parent is of type DerivedClass
}
The problem is that I have to enforce the type-matching myself when I declare DerivedClass
. There's nothing stopping someone from doing something like this:
public class DerivedClass1 : BaseClass<DerivedClass2>
{
// parent is of type DerivedClass2
}
Does C# have a way of doing this so that the type of a member declared in the base is sure to match the derived type?
I think this is similar to what this C++ question was trying to ask: Abstract base class for derived classes with functions that have a return type of the derived class