Answer the question
In order to leave comments, you need to log in
How to call a method depending on the value of a variable?
There is an object in the constructor of which a parameter is specified. The object must call the do() method, which, depending on the parameter, must execute another method. How to implement this without switch in c#?
Answer the question
In order to leave comments, you need to log in
It looks like you are trying to get this behavior. But yeah, it doesn't look like the best solution. Only I don’t understand where such categoricalness about the use of switch comes from
public class Class1
{
private readonly Action _action;
public Class1(string actionName)
{
switch (actionName)
{
case "1":
_action = Action1;
break;
case "2":
_action = Action2;
break;
default:
throw new Exception($"Unexpected action name {actionName}");
}
}
public void Act()
{
_action.Invoke();
}
private void Action1()
{
// ...
}
private void Action2()
{
// ...
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question