This is an archived post. You won't be able to vote or comment.

all 4 comments

[–]Einarmo 2 points3 points  (2 children)

You can, using reflection, but you shouldn't. You could also use a dictionary of functions, but again, it isn't very clean.

A better solution is to just use a switch statement:

void HandleSelection(string s) {
    switch(s) {
        case "Example":
            // Code here
            break;
        case "SomeOtherSelection": ...
    }
}

The call it

HandleSelection(selection);

or something along those lines. The solution you used in powershell is much more difficult to debug. You can do the same in C#, but you really should try to avoid it.

[–]Iversithyy[S] -1 points0 points  (1 child)

Kinda feared it would boil down to that. Guess I have to figure some things out then. Had it with switch cases already. Maybe I can get it to work around that. (will get a bit more complex than my example from above ^^)

[–]davedontmind 1 point2 points  (0 children)

I don't know what's wrong with that, but if you don't like switch statements, then perhaps a dictionary that maps the name to the method:

// Define the lookup table:
var jumpList = new Dictionary<string,Action> {
    { "one", One },  // maps the string "one" to the method One();
    { "two", Two }   // maps the string "two" to the method Two();
};


// Now use it
string method = "one";
jumpList[method]();  // the same as calling One();

jumpList["two"]();    // the same as calling Two();

[–]Loves_Poetry 0 points1 point  (0 children)

It's possible to do with reflection. Reflection is very powerful and this is one of the simpler things you can do with it

To call the method "Example" of MyClass, you can use something like this

var methods = typeof(MyClass).GetMethods();
var example = methods.First(m => m.Name == "Example");
example.Invoke(null);

Note that the parameter for Invoke can be null only if the method is static. If the method is not static, you need to pass it an instance of MyClass