-1

I am stuck at a point where I wanted a string to execute a function or event of my code. For example if

string somestr = "fun"; 

I want to execute a function called fun

public bool fun()
{
    return true;
}

I can manipulate somestr to like "execute fun" or "fun()" or something.

I best I could have thought till now is create a event or function where I should check and compare the string in switch case and execute the function or raise the event like

public void ReceivedCommand()
{
    if(somestr == "fun")
    {
        bool b = fun();
    }
    else if(somestr == "Otherfun")
    {
        //Some Other Function
    }
}

But now the case is that I have few hundreds of function and few events and user can choose any of them. I am very sure that there should be something that can solve my thing in a easy way instead writing lot of ifs and switch.

Could you please point me to the right direction how should I be able to do this.

1

3 Answers 3

1

You can use reflection to get the method that you want with it's name using Type.GetMethod(methodName). see this

2
  • 1
    Something like This right? Dec 1, 2016 at 7:09
  • Thanks for your time. I'll have a look
    – Mohit S
    Dec 1, 2016 at 7:15
1

You could do it dynamically like this

class MethodInvoker
{
    delegate void TestDelegate();

    public void fun()
    {
        Console.WriteLine("fun");
    }

    public void InvokeFromString(string functionName)
    {
        TestDelegate tDel = () => { this.GetType().GetMethod(functionName).Invoke(this, null); };
        tDel.Invoke();
    }
}

and use it like this

var test = new MethodInvoker();
test.InvokeFromString("fun");
1
  • Lemme try this. I am sure it is going to work. :)
    – Mohit S
    Dec 1, 2016 at 7:14
0

Use reflection. Something like this:

Type type = this.GetType();
MethodInfo methodInfo = type.GetMethod(somestr);
methodInfo.Invoke(this, userParameters);

// And this requires "using System.Reflection;" 

or

Try this link, i hope it works

4

Not the answer you're looking for? Browse other questions tagged or ask your own question.