-3

Well, been looking for this but since I cannot be more specific, Google seems out of answer, so I decided to ask here.

Anyway to create an array of methods that returns a value ?

Like

methodArray[0].Invoke();

Can I use delegate ? If so, how ?

like if i have 2 methods that needs same parameters

dobule Add(double number)
{
//code
}
double Remove(double number)
{
//code
}

what do i need to do in order to invoke them with index ( I dont want to deal with switch statement)

user1926930
  • 77
  • 1
  • 7

1 Answers1

3

You can create an array of Funcs. However, this is limited to methods that all have the same signature (return type and number and type of parameters).

If you have several methods that don't take any parameters you can use it like this:

var methods = new List<Func<T>>();

where T is the lowest common object in the return value, which might just be object.

var methods = new List<Func<object>>();

If you just want to call void methods, or aren't worried about the return type, you can use Action instead:

var methods = new List<Action>();

Either way, you can then invoke them like so:

foreach(var method in methods){
   var result = method();
   //or if you don't care about return type
   method();
}

You might also find this post useful: How do you use Func<> and Action<> when designing applications?

UPDATED The example below shows how you can use this technique with your Add and Remove method:

    public double Add(double number) { return 0;}
    public double Remove(double number) { return 0; }

    public void Example()
    {
        //Array of methods
        var methods = new Func<double, double>[]
        {
            n => Add(n),
            n => Remove(n)
        };

        //Invoking methods
        var number = 0d;
        foreach (var method in methods)
        {
            method(number);
        }
    }
Community
  • 1
  • 1
Philip Pittle
  • 11,821
  • 8
  • 59
  • 123