Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# call child method from parent list

I have the following problem: I have a list of UserControls for a wizard application and need to call a child method

List<UserControl> steps = new List<UserControl>();
steps.Add(new Step1());
steps.Add(new Step2());
steps.Add(new Step3());
steps.Add(new Step4());

All have StopTimeOut() method. How can I call: steps[0].StopTimeOut(); ?

Thank you.

like image 265
Miguel Cadaviz Avatar asked Dec 26 '22 23:12

Miguel Cadaviz


2 Answers

You should put the method in a common base class (eg, StepControl) and make all four controls inherit from it.

You can then make a List<StepControl> and call the function directly.

like image 95
SLaks Avatar answered Jan 12 '23 08:01

SLaks


Well, you already did it:

steps[0].StopTimeOut();

Just declare in base class of all Step classes StopTimeOut method as protected or public

Example:

public Step : UserControl {
    ....
    public virtual void StopTimeOut() {
         //BASE IMPLEMENTATION
    }
}

public Step1 : Step {
    public override void StopTimeOut() {
         //CHILD IMPLEMENTATION
    }
}

public Step2 : Step {
    public override void StopTimeOut() {
         //CHILD IMPLEMENTATION
    }
}
..

and in code:

List<Step> steps = new List<Step>();
steps.Add(new Step1());
steps.Add(new Step2());
..
like image 43
Tigran Avatar answered Jan 12 '23 06:01

Tigran