0

Possible Duplicate:
Calling a function from a string in C#

I would like to call one of the methods in a class from another class. The thing is that i don't know the method name in advance, i get it from external API..

Example:

class A
    public class Whichone
    {
        public static string AA() { return "11"; }
        public static string BB() { return "22"; }
        public static string DK() { return "95"; }
        public static string ZQ() { return "51"; }
        ..............
    }


class B
    public class Main
    {
        ........
        ........
        ........
        string APIValue = API.ToString();
        string WhichOneValue = [CALL(APIValue)];
    }

lets say the APIValue is BB then the value of WhichOneValue should be somehow 22. what is the right syntax to do that?

Community
  • 1
  • 1
user1199838
  • 103
  • 1
  • 13

2 Answers2

1

You could use reflection:

string APIValue = "BB";

var method = typeof(Whichone).GetMethod(APIValue);

// Returns "22"
// As BB is static, the first parameter of Invoke is null
string result = (string)method.Invoke(null, null);
ken2k
  • 48,145
  • 10
  • 116
  • 176
  • @user1199838 if `APIValue == "BB"`, it doesn't return null but a `MethodInfo` instance. – ken2k Feb 18 '12 at 10:38
1

This is called reflection. In your case, the code would look like this:

string WhichOneValue =
    (string)typeof(Whichone).GetMethod(APIValue).Invoke(null, null);

One of the disadvantages of reflection is that it is slower than normal method invocation. So, if profiling shows that calling the method like this is too slow for you, you should consider alternatives, like Dictionary<string, Action>, or Expressions.

svick
  • 236,525
  • 50
  • 385
  • 514