Resolved How do you easily choose from many methods?

glasswizzard

Well-known member
Joined
Nov 22, 2019
Messages
126
Programming Experience
Beginner
I need to write a method that will call one of many other methods, I know I could write a huge switch statement to get to the right call but is there an easier way?
I have a string that could be used to get the name of the method to call if that's any help.

Thanks
 
Research "C# reflection"
 
If there's a string or other value/object that should map to the method you could set up a dictionary of delegates:
C#:
var methods = new Dictionary<string, Action>()
{
    { "A", () => MethodA() },
    { "B", () => MethodB() },
    { "C", () => MethodC() }
};
and call it by key:
C#:
methods["A"]();
 
If there's a string or other value/object that should map to the method you could set up a dictionary of delegates:
C#:
var methods = new Dictionary<string, Action>()
{
    { "A", () => MethodA() },
    { "B", () => MethodB() },
    { "C", () => MethodC() }
};
and call it by key:
C#:
methods["A"]();

This seems to be just what I need. I looked up the action keyword and it seems to be used only for methods that don't return a value, the methods I'm calling will return one and also take a value. Would I need to replace the action keyword with func?
 
Yes, that is the correct and robust object oriented solution, but it saves our OP very little typing. If he has hundreds of methods, he would still have to type in hundreds of dictionary entries.
 
I was curious about what the cost (in typing) of switch case statement vs dictionary initialization. Here's what I came up with:
C#:
case "A": MethodA(); break;
{ "A", () => MethodA(); },
["A"] = () => MethodA(),
["A"] = MethodA,
 
This seems to be just what I need. I looked up the action keyword and it seems to be used only for methods that don't return a value, the methods I'm calling will return one and also take a value. Would I need to replace the action keyword with func?
Yes, you can use any delegate that match the method signature. Func<T,TResult> Delegate (System)
 
I was curious about what the cost (in typing) of switch case statement vs dictionary initialization. Here's what I came up with:
C#:
case "A": MethodA(); break;
{ "A", () => MethodA(); },
["A"] = () => MethodA(),
["A"] = MethodA,
The lambda was unnecessary in my example, could be:
C#:
{ "A", MethodA },
 
I wonder what the performance difference is using this compared to a simple switch. Any volunteers here want to see which is faster and test it?
 
I didn't want to assume, but I did suspect the Dictionary may have had some performance gains here, but I will hopefully test this tomorrow if I can find the time. Probably won't happen, since I'm up to my elbows in work these days.
 
Back
Top Bottom