B
B
BitNeBolt2020-07-02 09:56:01
OOP
BitNeBolt, 2020-07-02 09:56:01

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

2 answer(s)
A
ayazer, 2020-07-02
@BitNeBolt

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()
        {
            // ...
        }
    }

V
Vladimir Korotenko, 2020-07-02
@firedragon

if(arg == 'one') this.doOne();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question