Link to home
Start Free TrialLog in
Avatar of paul-uk
paul-uk

asked on

C# converting a string into a function call

Hi,
Using C# how can I turn a string into a function call e.g.

Doing this:
string functionName = "SMA";
int result = functionName();

would be the same as doing this:
int result = SMA();

Thanks


ASKER CERTIFIED SOLUTION
Avatar of Mike Tomlinson
Mike Tomlinson
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Reflection is the way to do it.

Assuming  SMA() is defined like this

class MyClass{
  private int SMA(){
    return 1;
  }
}
MyClass foo = new MyClass();
 
MethodInfo mi = foo.GetType().GetMethod("SMA",
  BindingFlags.Instance | BindingFlags.NonPublic);
 
int i = (int)mi.Invoke(foo, null);

Open in new window

Caveman method

 Dictionary<string,function>  funcmap = new ....;

 funcmap["SMA"] = functionName ();
 funcmap["Other"] = functionOther ();

  callfunc( string funcname )
  {
      int result = funcmap[funcname];
 }

Avatar of paul-uk
paul-uk

ASKER

Thanks all for the solutions.
Does using Reflection have a significant impact on performance?
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of paul-uk

ASKER

Thanks this has been very helpful.
Using Reflection, while giving me the flexibility I would like, will not give me the speed I need. "Invoke" could be called multiples of thousands of times depending on the size of the data set being used in my application. Standard function calls seems to be the way to go.
In some cases I've used a switch to catch common method names and directly call the functions. The default option uses reflection.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial