Search code examples
c#inheritancemethodsmultiple-inheritance

Call ALL children methods of a class from another class


Lets say that i have a "Timer" class with a method that every 1 second is called, and it calls another method in the class "Gear":

public class Timer
{
    public void OnTick()
    {
        Gear.Update();
    }
}

public class Gear
{
    public static void Update() { }
}

This kinda works, but it's only called on the base class. The method "Update" should be called in all the childrens of "Gear": e.g:

public class AnotherClass : Gear
{
    public override void Update() { // do stuff }
}
public class YetAnotherClass : Gear
{
    public override void Update() { // do stuff }
}
public class AndAnotherClass : Gear
{
    public override void Update() { // do stuff }
}

How can i do this?


Solution

  • In order for the code to work the way you want, you'd need to do something like this (I would worry about a memory leak):

    public abstract class Gear
    {
        readonly static List<Gear> gears = new List<Gear>();
    
        public Gear()
        {
            gears.Add(this);
        }
    
        public static void Update()
        {
            foreach (var gear in gears)
                gear._Update();
        }
    
        protected abstract void _Update();
    }
    
    
    public sealed class Gear1 :  Gear
    {
        protected override void _Update()
        {
            //do stuff
        }
    }
    
    public sealed class Gear2 : Gear
    {
        protected override void _Update()
        {
            //do stuff
        }
    }
    
    public sealed class Gear3 : Gear
    {
        protected override void _Update()
        {
            //do stuff
        }
    }
    
    
    public static void Main(string[] args)
    {
        var timer = 
              new Timer(o => Gear.Update(), null, 0, SOME_INTERVAL);                       
    }
    

    However, you might be better off by defining the base case thusly:

    public abstract class Gear
    {
        public abstract void Update();
    }
    

    And then define a collection class:

    public sealed class GearCollection : List<Gear>
    {        
        public void Update()
        {
            foreach (var gear in this)
                gear.Update();
        }
    }
    

    And then

    public static void Main(string[] args)
    {
        var gears = new GearCollection();
    
        //add gear instancs to gears
    
        var timer = new Timer(o => gears.Update(), null, 0, SOME_INTERVAL);            
    }