c# – Is it possible to add cases to a swich dynamically (at runtime)? C #

Question:

I wonder if it is possible to add cases to a switch at runtime. That is, start with an empty switch like the following:

switch (opcion)
        {
            default:
                 break;
        }

And then add cases if necessary

switch (opcion)
        {
            case Case1:
                {
                  break;
                }

                .....
                .....
                .....
            case CaseN:
                {

                    break;
                }
            default:
                 break;
        }

Say that I have made a code that "emulates" (more or less) what I want to do and is the following:

//--------------------------------------------------------------
public class DinamicSwith<T> where T : IComparable
{
    public delegate T Delegate();
    public List<Delegate> caseList;
    public List<T> option;
    public Delegate Default;
    T defaultReturn;
    bool isDefaultSet;

    public DinamicSwith(T defaultReturn)
    {
        caseList = new List<Delegate>();
        option = new List < T >();
        this.defaultReturn = defaultReturn;
    }
    public void AddCase(Delegate func, T option)
    {        
        caseList.Add(func);
        this.option.Add(option);
    }
    public void AddDefault(Delegate func)
    {
        Default = func;
        isDefaultSet = true;
    }
    public T Execute(T option)
    {
        for (int i = 0; i < caseList.Count; i++)
        {
            if (this.option[i].CompareTo(option)==0)
            {
                return caseList[i]();
            }
        }

        if(isDefaultSet)    
            Default();

        return defaultReturn;
    }
}
//--------------------------------------------------------------

What I want to know is if there is any way to do it "by default" … that is, a method provided by the C # language itself (a simpler and more efficient way). Thanks!!

Answer:

Actually what you are doing is a map , in pseudo code it would be something like this:

Map<Case, Function> switch = ...
Function fun;
if (switch.hasKey(myCase)) {
    fun = switch.get(MyCase);

} else {
    fun = switch.get(DEFAULT);
}
fun(...);

At any time you could add new "cases", associated with a new function. This could be done in any programming language. And really the switches are usually transformed when compiling to a hash table so as not to have to compare case by case and that any input is resolved in O (1), no matter how many cases there are (your implementation goes through all of them until it finds the one that is complies).

Scroll to Top