0

I have a collection of strings. For example,

string[] coll={"1", "2", "3" ..."100"..."150"...} 

and I have respective methods for the string collection such as

void Method1, void Method2, void Method100

I select appropriate method like that:

string selector=string.Empty;
switch(selector)
 { case "1": 
            MethodOne();
            break;
    ........
    case "150":
            Method150();
            break;
  }

The above code is really bored and I will have more string elements in the string collection {"150" ... "250"...}. How to make like that:

 string sel=col[55];
 if(sel!=null)
        // call here the respective         method(method55)

I do not want to use switch operator cause it gives rise to surplus of code.

MBoros
  • 1,090
  • 7
  • 19
StepUp
  • 36,391
  • 15
  • 88
  • 148

3 Answers3

2

Solution 1:

Use a delegate mapping. This is the faster solution.

private static Dictionary<string, Action> mapping =
    new Dictionary<string, Action>
    {
        { "1", MethodOne },
        // ...
        { "150", Method150 }
    };

public void Invoker(string selector)
{
    Action method;
    if (mapping.TryGetValue(selector, out method)
    {
        method.Invoke();
        return;
    }

    // TODO: method not found
}

Solution 2:

Use reflection. This is slower and is appropriate only if your methods have strict naming (eg. 1=MethodOne 150=Method150 will not work).

public void Invoker(string selector)
{
    MethodInfo method = this.GetType().GetMethod("Method" + selector);
    if (method != null)
    {
        method.Invoke(this, null);
        return;
    }

    // TODO: method not found
}
György Kőszeg
  • 17,093
  • 6
  • 37
  • 65
  • You can also combine the two solutions: have a dictionary of delegates and fill it using reflection. That gives you the efficiency of solution 1, while not repeating code like solution 2. – svick Aug 23 '15 at 11:39
1

You can use dynamic invocation

 var methodName = "Method" + selector;
 var method = this.GetType().GetMethod(methodName);
 if (method == null)
 {
    // show error
 }
 else
    method.Invoke(this, null);
Richard Schneider
  • 34,944
  • 9
  • 57
  • 73
1

You can declare a dictionary with your keys and actions like

Dictionary<string, Action> actions = new Dictionary<string, Action>()
{
    { "1", MethodOne },
    { "2", ()=>Console.WriteLine("test") },
    ............
};

and invoke it as

actions["1"]();

PS: Presuming method void MethodOne(){ } is declared somewhere.

Eser
  • 12,346
  • 1
  • 22
  • 32
  • Maybe you know how to call "void MethodOne(int x)"? Method with parameter – StepUp Aug 20 '15 at 13:16
  • 1
    @StepUp `()=>MethodOne(i)` ? Maybe declaring `Dictionary>` and then `actions["1"](i)`. Depends on your case... – Eser Aug 20 '15 at 13:23