-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.

Mohit S
  • 13,723
  • 6
  • 34
  • 69
  • 1
    Check this out http://stackoverflow.com/questions/6469027/call-methods-using-names-in-c-sharp – Prajwal Dec 01 '16 at 07:07

3 Answers3

1

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

Emad
  • 3,809
  • 3
  • 32
  • 44
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");
Pepernoot
  • 3,409
  • 3
  • 21
  • 46
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

  • Are you sure? Lemme give it a try. But it seems its is not going to work. – Mohit S Dec 01 '16 at 07:16
  • It works, check this http://viralpatel.net/blogs/calling-javascript-function-from-string/ –  Dec 01 '16 at 07:17
  • It's not a Javascript question. Look at the tags. – elshev Dec 01 '16 at 07:20
  • y, i saw : Use this link - https://www.codeproject.com/articles/19911/dynamically-invoke-a-method-given-strings-with-met –  Dec 01 '16 at 07:24