Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Make a List to hold any derived children of a base class

Tags:

c#

inheritance

So I wish to setup an abstract base class to derive children classes from. All the work will take place on the children, but I wanted the children to be able to reference each other.

Here is some pseudo-code:

public abstract class BaseClass<T> : SomeOtherClass {

    public List<BaseClass> listOfChildren;

    protected T thisChild;

    public void DoMoreStuff(){
        Debug.Log("Doing more stuff");
    }

    protected virtual void DoSomething(int i){
        listOfChildren[i].DoMoreStuff();
    }
}

public class FirstChildClass : BaseClass<FirstChildClass> {

    FirstChildClass<T>(){
        thisChild = this;
    }

    public void FirstClassStuff(){
        Debug.Log("first class stuff");
    }

}
public class SecondChildClass : BaseClass<SecondChildClass> {

    public void SecondClassStuff(){
        Debug.Log("second class stuff");
    }
}

How would I make a generic List to accept any child class?

Will I need to typecast listOfChildren with T to use DoMoreStuff()?

On its own, is there anything else inherently wrong with this setup?

like image 606
user1297102 Avatar asked Jan 14 '23 15:01

user1297102


1 Answers

I think you overcompicate the solution. If you don't want to store any data in each node - try to solve this problem then without the generics. I will give you a naive straight-forward implementation of desired behavior as a starting point.

public abstract class BaseClass  {

    private IList<BaseClass> children = new List<BaseClass>();

    public void AddChild(BaseClass child)
    {
        this.children.Add(child);
    }

    protected virtual void DoMoreStuff(){
        Debug.Write("Doing more stuff");
    }

    public void DoSomething(int i){
        children[i].DoMoreStuff();
    }
}

public class FirstChildClass : BaseClass {

    protected override void DoMoreStuff(){
        Debug.Write("first class more stuff");
    }

}

public class SecondChildClass : BaseClass {

    protected override void DoMoreStuff(){
        Debug.Write("second class more stuff");
    }
}

now you can

var root = new FirstChildClass();

root.AddChild(new FirstChildClass());
root.AddChild(new SecondChildClass());
root.AddChild(new FirstChildClass());

root.DoSomething(1); //will print second class more stuff
root.DoSomething(0); //will print first class more stuff
like image 171
Ilya Ivanov Avatar answered Feb 12 '23 11:02

Ilya Ivanov