Reputation: 280
I am having some difficulty with this. I have an abstract class, and I would like to add a public abstract method for its inheritors to implement. The challenge is that the method should return a generic list of classes that implement a totally different abstract class (NotifyingDatabaseObject).
I'd like to do something like the following, but it won't compile:
public abstract IList<T> GetList(int? id) where T : NotifyingDatabaseObject;
And, of course, if I replace "T" with "NotifyingDatabaseObject", it will require the inheriting classes to return that abstract class instead of concrete ones.
Any direction on how I can accomplish this?
Thanks!
Upvotes: 1
Views: 1472
Reputation: 144176
I assume you want each subclass of your base class to return a particular subtype of NotifyingDatabaseObject
. In this case you should add a type parameter to the base class and have each subtype specify which subtype of NotifyingDatabaseObject
they return:
public abstract class MyAbstractClass<T>
where T : NotifyingDatabaseObject
{
public abstract IList<T> GetList(int? id) ;
}
public class MyConcreteClass : MyAbstractClass<NotifyingDatabaseObjectChildClass>
{
public override IList<NotifyingDatabaseObjectChildClass> GetList(int? id)
{
return new List<NotifyingDatabaseObjectChildClass>();
}
}
Note the existing answer does not do this - it requires each subtype to support returning a list of any subtype of NotifyingDatabaseObject
, not just one in particular. In this case the only possible implementation is to return an empty list (or null, or throw an exception, or loop infinitely), since the implementing classes have no general way of constructing a value of type T
.
Upvotes: 2
Reputation: 5767
If the returning type has no relation to the abstract or the concrete class, you can use a type parameter on the method, like:
public abstract IList<T> GetList<T>(int? id) where T : NotifyingDatabaseObject;
The concrete class would be something like:
class MyConcreteClass : MyAbstractClass
{
public override IList<NotifyingDatabaseObjectChildClass> GetList<NotifyingDatabaseObjectChild>(int? id)
{
return new List<NotifyingDatabaseObjectChildClass>();
}
}
Upvotes: 3