Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using 'switch' with strings in resource file

I have a bunch of strings in my resource(.resx) file. I am trying to directly use them as part of switch statement (see the sample code below).

class Test
{
    static void main(string[] args)
    {
        string case = args[1];
        switch(case)
        {
            case StringResources.CFG_PARAM1: // Do Something1 
                break;
            case StringResources.CFG_PARAM2: // Do Something2
                break;
            case StringResources.CFG_PARAM3: // Do Something3
                break;              
            default:
                break;
        }
    }
}

I looked at some of the solutions, most of them seem to suggest that I need to declare them as const string which I personally dislike. I liked the top voted solution for this question: using collection of strings in a switch statement. But then I need to make sure that my enum and strings in resource file are tied together. I would like to know a neat way of doing that.

Edit: Also found this great answer while researching how to use Action:

like image 595
rkg Avatar asked Feb 23 '11 21:02

rkg


People also ask

Can you do a switch statement with Strings?

Yes, we can use a switch statement with Strings in Java.

Is switch case case sensitive in c#?

The comparison perform between String objects in switch statements is case sensitive. You must use break statements in switch case.


2 Answers

You could use a Dictionary<string, Action>. You put an Action (a delegate to a method) for each string in the Dictionary and search it.

var actions = new Dictionary<string, Action> {
    { "String1", () => Method1() },
    { "String2", () => Method2() },
    { "String3", () => Method3() },
};

Action action;

if (actions.TryGetValue(myString, out action))
{
    action();
}
else
{
    // no action found
}

As a sidenote, if Method1 is already an Action or a void Method1() method (with no parameters and no return value), you could do

    { "String1", (Action)Method1 },
like image 71
xanatos Avatar answered Oct 04 '22 02:10

xanatos


You can't do that. The compiler must be able to evaluate the values, which means that they need to be literals or constants.

like image 26
Fredrik Mörk Avatar answered Oct 04 '22 03:10

Fredrik Mörk