galaxyan
galaxyan

Reputation: 83

How to merge two case statements in one switch statement

switch(code)
{
    case 'A':
    case 'a':
         // to do 
    default:
         // to do 
}

Is there any way to merge the two "case" statements together?

Upvotes: 8

Views: 25517

Answers (3)

davbryn
davbryn

Reputation: 7176

Switch will evaluate for every condition met until it hits a break, a default or the final closing bracket.

i.e it will execute any matching case statement until it hits one of those instructions.

Groups all equivilant cases and add a break after the last to merge them.

Be aware that if there are no matches, it will fall into the default block.

Upvotes: 0

IgorM
IgorM

Reputation: 1356

http://msdn.microsoft.com/en-us/library/06tc147t.aspx

class Program
{
    static void Main(string[] args)
    {
        int switchExpression = 3;
        switch (switchExpression)
        {
            // A switch section can have more than one case label. 
            case 0:
            case 1:
                Console.WriteLine("Case 0 or 1");
                // Most switch sections contain a jump statement, such as 
                // a break, goto, or return. The end of the statement list 
                // must be unreachable. 
                break;
            case 2:
                Console.WriteLine("Case 2");
                break;
                // The following line causes a warning.
                Console.WriteLine("Unreachable code");
            // 7 - 4 in the following line evaluates to 3. 
            case 7 - 4:
                Console.WriteLine("Case 3");
                break;
            // If the value of switchExpression is not 0, 1, 2, or 3, the 
            // default case is executed. 
            default:
                Console.WriteLine("Default case (optional)");
                // You cannot "fall through" any switch section, including
                // the last one. 
                break;
        }
    }
}

Upvotes: 2

Habib
Habib

Reputation: 223207

You just need break; for your current code like:

switch (code)
{
    case 'A':
    case 'a':
        break;
    // to do 
    default:
        // to do 
        break;
}

but if you are comparing for upper and lower case characters then you can use char.ToUpperInvariant and then specify cases for Upper case characters only:

switch (char.ToUpperInvariant(code))
{
    case 'A':
        break;
    // to do 
    default:
        // to do 
        break;
}

Upvotes: 17

Related Questions