Click here to Skip to main content
15,885,757 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Can I use an if statement in a switch case like this?

VB
switch(abc)

case"a"
if
{}
else
Posted
Updated 19-Oct-11 22:25pm
v3
Comments
Dalek Dave 20-Oct-11 4:25am    
Edited for Code Block

Yes you can put anything in your case statement up to the break
C#
switch(abc)
{
    case "a" :
        if (something)
        {
        }
        else
        {
        }
    break;
}
 
Share this answer
 
Comments
RaisKazi 20-Oct-11 2:59am    
My 5! Seems we both posted at almost same time. :)
Yes certainly you can do this. Try as below code.

C#
string abc = "a";
string output = string.Empty;

switch(abc)
{
    case "a":
        if (1 == 1) //some sample condition
        {
            output = "a";
        }
        break;
    case "b":
        if (1 == 1) //some sample condition
        {
            output = "b";
        }
        break;
}
 
Share this answer
 
Comments
Mehdi Gholam 20-Oct-11 3:06am    
my 5 also!
Yes we can have if statement inside switch, try this
C#
switch (number.ToString().Length)
    {
        case 3:
            ans += string.Format("{0} hundred and ", numbers[number / 100]);
        case 2:
            int t = (number / 10) % 10;
            if (t == 1)
            {
                ans += teens[number % 10];
                break;
            }
            else if (t > 1)
             {
                ans += teens[t];
                break;
             }
        case 1:
            int o = number % 10;
            ans += numbers[o];

            break;
        default:
            throw new ArgumentException("number");
    }
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900