use Switch condition with string and int datatype in C#

In this post show sample code of switch condition with string and int datatype in C#. Let's examine code below:

Switch with string datatype:

   Syntax :
       Switch(variable)
   {
         case "string_value1":
                            statement(s);
                            break;
        case "string_value2":
                            statement(s);
                            break;
        default :
                          statement(s);
                          break;
    }
code :
 string thing =TextBox1.Text;
 switch (thing)
 {
    case "pen":
         Label1.Text="You choose a pen";
         break;
    case "bag":
         Label1.Text="You choose a bag";
         break;
    case "drink":
         label1.Text="You choose a drink";
         break;
    default:
         Label1.Text="You can choose only 3 things";
         break;

 }

Switch with integer datatype:

     Syntax :  
     Switch(variable)
   {
         case int_value1:
                            statement(s);
                            break;
        case int_value2:
                            statement(s);
                            break;
        default :
                          statement(s);
                          break;
    }
code :
  int option =Convert.ToInt32(TextBox1.Text);
  switch (option)
  {
     case 1:
         Label1.Text="You choose option 1";
         break;
     case 2:
         Label1.Text="You choose option 2";
         break;
     case 3:
         label1.Text="You choose a drink";
         break;
     default:
         Label1.Text="You choose wrong option";
         break;
    }
Hope this post is helpful for you.......:) :) 
use Switch condition with string and int datatype in C# use Switch condition with string and int datatype in C# Reviewed by BeiLover on 5:51 PM Rating: 5

No comments:

Powered by Blogger.