[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 434
  • Last Modified:

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


0
paul-uk
Asked:
paul-uk
3 Solutions
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
Simple case scenario using Reflection:
    public partial class Form1 : Form
    {
 
        private void button1_Click(object sender, EventArgs e)
        {
            string methodName = "SMA";
            Type t = this.GetType();
            MethodInfo mi = t.GetMethod(methodName, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
            if (mi != null)
            {
                int result = (int)mi.Invoke(this, new Object[] { });
                MessageBox.Show("result = " + result.ToString());
            }
        }
 
        private int SMA()
        {
            return -1;
        }
 
    }

Open in new window

0
 
oobaylyCommented:
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

0
 
williamcampbellCommented:
Caveman method

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

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

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

0
Transaction-level recovery for Oracle database

Veeam Explore for Oracle delivers low RTOs and RPOs with agentless transaction log backup and transaction-level recovery of Oracle databases. You can restore the database to a precise point in time, even to a specific transaction.

 
paul-ukAuthor Commented:
Thanks all for the solutions.
Does using Reflection have a significant impact on performance?
0
 
oobaylyCommented:
Yup, using Reflection can be almost two orders of magnitude slower than a standard call. As you can see from the results, the expensive part of reflection isn't getting the MethodInfo from the type, but is the Invoke.
These numbers were done in Debug mode, while execute times are lower for release the same massive difference between types of call exist.

Count      Std. Call      Reflection #1      Reflection #2
10000      0      78.13      62.5
100000      15.63      750      609.38
1000000      78.13      7500      6031.25
10000000      750      75062.5      60031.25

private static void BenchmarkReflection(int count) {
  // Std. Call
  DateTime start = DateTime.Now;
  for (int i = 0; i < count; i++) {
    bool b = (bool)FooBar(null);
  }
  TimeSpan elapsed = DateTime.Now.Subtract(start);
  Console.WriteLine(elapsed.TotalMilliseconds.ToString());
 
  // Reflection #1
  start = DateTime.Now;
  for (int i = 0; i < count; i++) {
    MethodInfo mi = typeof(Program).GetMethod("FooBar", BindingFlags.Static | BindingFlags.NonPublic);
    bool b = (bool)mi.Invoke(null, new object[] { null });
  }
  elapsed = DateTime.Now.Subtract(start);
  Console.WriteLine(elapsed.TotalMilliseconds.ToString());
 
  // Reflection #2
  start = DateTime.Now;
  MethodInfo mi2 = typeof(Program).GetMethod("FooBar", BindingFlags.Static | BindingFlags.NonPublic);
  for (int i = 0; i < count; i++) {
    bool b = (bool)mi2.Invoke(null, new object[] { null });
  }
  elapsed = DateTime.Now.Subtract(start);
  Console.WriteLine(elapsed.TotalMilliseconds.ToString());
}
 
private static bool FooBar(object obj) {
  return (rand.Next(0, 2) == 0);
}

Open in new window

0
 
paul-ukAuthor Commented:
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.
0
 
Tony McCreathTechnical SEO ConsultantCommented:
In some cases I've used a switch to catch common method names and directly call the functions. The default option uses reflection.
0
 
crazymanCommented:
http://www.codeproject.com/KB/cs/Dynamic_Code_Generation.aspx

We have used this before, it can generate the method in IL the first time you use it then subsequent calls use the generated code..

Works well
0

Featured Post

Microsoft Certification Exam 74-409

VeeamĀ® is happy to provide the Microsoft community with a study guide prepared by MVP and MCT, Orin Thomas. This guide will take you through each of the exam objectives, helping you to prepare for and pass the examination.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now