views:

1532

answers:

4

I have the following structure:

abstract class Base {
        public abstract List<...> Get(); //What should be the generic type?
}

class SubOne : Base {
    public override List<SubOne> Get() {

    }
}

class SubTwo : Base {
    public override List<SubTwo> Get() {

    }
}

I want to create an abstract method that returns whatever class the concrete sub class is. So, as you can see from the example, the method in SubOne should return List<SubOne> whereas the method in SubTwo should return List<SubTwo>.

What type do I specify in the signature declared in the Base class ?


[UPDATE]

Thank you for the posted answers.

The solution is to make the abstract class generic, like such:

abstract class Base<T> {
        public abstract List<T> Get();
}

class SubOne : Base<SubOne> {
    public override List<SubOne> Get() {

    }
}

class SubTwo : Base<SubTwo> {
    public override List<SubTwo> Get() {

    }
}
+6  A: 

Your abstract class should be generic.

abstract class Base<T> {
        public abstract List<T> Get(); 
}

class SubOne : Base<SubOne> {
    public override List<SubOne> Get() {

    }
}

class SubTwo : Base<SubTwo> {
    public override List<SubTwo> Get() {
    }
}

If you need to refer to the abstract class without the generic type argument, use an interface:

interface IBase {
        //common functions
}

abstract class Base<T> : IBase {
        public abstract List<T> Get(); 
}
recursive
Excellent, exactly what I was looking for. Thank you
Andreas Grech
Dang, I have *got* to learn to type faster.
Jim H.
+1  A: 

I don't think you can get it to be the specific subclass. You can do this though:

abstract class Base<SubClass> {
        public abstract List<SubClass> Get(); 
}
class SubOne : Base<SubOne> {
    public override List<SubOne> Get() {
        throw new NotImplementedException();
    }
}
class SubTwo : Base<SubTwo> {
    public override List<SubTwo> Get() {
        throw new NotImplementedException();
    }
}
eglasius
A: 

Try this:

public abstract class Base<T> {
  public abstract List<T> Foo();
}

public class Derived : Base<Derived> {   // Any derived class will now return a List of
  public List<Derived> Foo() { ... }     //   itself.
}
John Feminella
+2  A: 
public abstract class Base<T> 
{       
    public abstract List<T> Get(); 
}

class SubOne : Base<SubOne> 
{
    public override List<SubOne> Get() { return new List<SubOne>(); }
}

class SubTwo : Base<SubTwo> 
{
    public override List<SubTwo> Get() { return new List<SubTwo>(); }
}
Mitch Wheat