Search code examples
c#foreachconditional-statementsswitch-statementiteration

Non Static/Constant values in case statements within a Switch


I would like to evaluate a dynamic string value within a switch statement in C#.

For example:

int i = 0;
foreach (Item item in _Items)
{
    foreach (Field theField in doc.Form.Fields)
    {
        switch (theField.Name)
        {
            case "Num" + i++.ToString(): // Dynamic Evaluation?
                theField.Value = string.Empty;
                break;
        }
    }
}

I have 20 or so fields named Num1, Num2, etc. If I can do this all in one statement/block, I'd prefer to do so.

But the compiler complains that the case statements need to be constant values. Is there a way to use dynamic variables in the case statement so I can avoid repeating code?

I just thought I'd mention, the purpose of this method is to populate the fields in PDF form, with naming conventions which I can not control. There are 20 rows of fields, with names like "Num1" - "Num20". This is why string concatenation would be helpful in my scenario.


Solution

  • No. This is simply part of the language. If the values aren't constants, you'll have to use if/else if or a similar solution. (If we knew more details about what you were trying to achieve, we may be able to give more details of the solution.)

    Fundamentally, I'd question a design which has a naming convention for the fields like this - it sounds like really you should have a collection to start with, which is considerably easier to work with.