Specifying the return type of an abstract method from a Base Class according to a Sub Class

21,358

Solution 1

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(); 
}

Solution 2

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>(); }
}

Solution 3

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.
}

Solution 4

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();
    }
}
Share:
21,358
Andreas Grech
Author by

Andreas Grech

+++++[&gt;+++++[&gt;++++&lt;-]&lt;-]&gt;&gt;+++.--..++++++. Contactable at $(echo qernfterpu#tznvy?pbz | tr ?a-z# .n-za-m@)

Updated on July 05, 2022

Comments

  • Andreas Grech
    Andreas Grech almost 2 years

    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() {
    
        }
    }