As others have noted, there are several ways to simulate this, but there are no “baked” features in C #. The most flexible way is with reflection, but you can make it much easier (and easier to deal with) if you know the list of methods that you will name in advance.
class Foo { public static string FooA(int p1, int p2) { return "FooA:" + p1 + p2; } public static string FooB(int p1, int p2) { return "FooB:" + p1 + p2; } public static string FooC(int p1, int p2) { return "FooC:" + p1 + p2; } } class Bar { //You can use Func<int, int, object> instead of a delegate type, //but this way is a little easier to read. public delegate string Del(int p1, int p2); public static string DoStuff() { var classes = new Dictionary<string, Dictionary<string, Del>>(); classes.Add("Foo", new Dictionary<string, Del>()); classes["Foo"].Add("FooA", Foo.FooA); classes["Foo"].Add("FooB", Foo.FooB); classes["Foo"].Add("FooC", Foo.FooC); //...snip... return classes["Foo"]["FooA"](5, 7); } }
Which, by the way, works.
If you do not know what methods you want to make available in this way, I suggest that you review everything that you are trying to do. The only reason I can think of using strings to select the execution path will be if you plan to get these strings from the user. Not only does the sheer amount of no-no reveal the internal details of your application like this, but it is dangerously close to the eval -type functionality. There is a reason why C # does not have an eval method, and not because designers forgot to insert it.
source share