Jester Jester - 3 months ago 10
C# Question

Accessing the correct function in an ArrayList of different child classes

Say I have the following three classes:

Parent class:

public class ParentClass {
public void foo() {
Debug.Log("Parent called!");
}
}


First child class:

public class ChildOne : ParentClass {
public new void foo() {
Debug.Log("Child one called!");
}
}


Second child class:

public class ChildTwo : ParentClass {
public new void foo() {
Debug.Log("Child two called!");
}
}


In a fourth class, I have an ArrayList that contains multiple ChildOne and ChildTwo objects. The ArrayList doesn't contain any objects of other types.

How do I access the foo() functions of the child objects?

public class Example {
public void someFunction() {
//...

ArrayList children = new ArrayList();
children.add(new ChildOne());
children.add(new ChildTwo());

children[0].foo(); //here I want to call the foo() function of the ChildOne object
children[1].foo(); //here I want to call the foo() function of the ChildTwo object

//...
}
}


Casting to ParentClass doesn't work, and I can't cast to one of the child classes because I don't know the type of each element.

Answer

If you can, you could use polymorphism instead of hiding the parent's foo function.

To achieve this result, we can transform the parent class to make the foo method virtual so we can override it in child class :

public class ParentClass {
    public virtual void foo() {
        Debug.Log("Parent called!");
    }
}

Then in the children classes, we replace the new keyword by the override keyword :

public class ChildOne : ParentClass {
    public override void foo() {
        Debug.Log("Child one called!");
    }
}

public class ChildTwo : ParentClass {
    public override void foo() {
        Debug.Log("Child two called!");
    }
}

Using an ArrayList, you would call the foo method this way :

ArrayList children = new ArrayList();
children.Add(new ChildOne());
children.Add(new ChildTwo());
(children[0] as ParentClass).foo(); // will display "Child one called!"

Please not that children[0] returns an object. You have to cast this object to ParentClass to be able to call the foo method.

My last suggestion would be to use a List instead of the ArrayList. A List is strongly typed and you don't have to cast anything.

var children = new List<ParentClass>();
children.Add(new ChildOne());
children[0].foo(); // will display "Child one called!"
Comments