Ruben Hamers
Ruben Hamers

Reputation: 293

Array containing Methods

I was wondering if you can create an Array or a List<> that contains methods. I don't want to use a switch or lots of if statements.

Thanks

Upvotes: 21

Views: 29499

Answers (5)

Tomas Dale
Tomas Dale

Reputation: 1

object[] arrProc = new object[2];

arrProc[0] = (string)Fx1();

arrProc[1] = (string)Fx2();

string aa = (string)arrProc[0];

Upvotes: -1

Jens
Jens

Reputation: 25593

Yes, it is possible to have such an array or list. Depending on the number of input or output parameters, you'd use something like

List<Func<T1, T2, TReturn>>

An instance of type Func<T1, T2, TReturn> is a method like

TReturn MyFunction(T1 input1, T2 input2)

Take a look at the MSDN.

Upvotes: 9

Pete Houston
Pete Houston

Reputation: 15089

There you go

List<Action> list = new List<Action>();
list.Add( () => ClassA.MethodX(paramM) );
list.Add( () => ClassB.MethodY(paramN, ...) );

foreach (Action a in list) {
    a.Invoke();
}

Upvotes: 20

antonisCSharp
antonisCSharp

Reputation: 11

Maybe you want to try this if u don't want to use Lists

public    Action[] methods;

private void methodsInArray()
{

    methods= new Action[2];
    methods[0] = test ;
    methods[1] = test1;
}

private void test()
{
    //your code
}

private void test1()
{
    //your code
}

Upvotes: 1

Jonas Elfstr&#246;m
Jonas Elfstr&#246;m

Reputation: 31468

If you are trying to replace a switch then a Dictionary might be more useful than a List

var methods = new Dictionary<string, Action>()
              {
                  {"method1", () => method1() },
                  {"method2", () => method2() }
              };

methods["method2"]();

I consider this and switch statements a code smell and they can often be replaced by polymorphism.

Upvotes: 3

Related Questions