www.pickatutorial.com Computer Tutorials
Top eBooks: C/C++ | C# | Android | Mathematics | Database | Cloud | Graphics | Networking | Oracle | Hardware | AI
Top Tutorials: C/C++ | C#.NET | PHP MySQL | Java | Java Script | jQuery | HTML | xHTML | HTML5 | VB Script| CSS
Lessons C# switch Bookmark and Share
Tutorial Home
Lesson 1
Lesson 2
Lesson 3
Lesson 4
Lesson 5
Lesson 6
Lesson 7
Lesson 8
Lesson 9
Lesson 10
Lesson 11
Lesson 12
Lesson 13
Lesson 14
Lesson 15
Lesson 16
Lesson 17
Lesson 18
Lesson 19
Lesson 20
Lesson 21
Lesson 22
Lesson 23
C# supports a number of control statements including break, continue, goto, if, switch, return, and throw. They are more or less similar to their counterparts in C++. The switch statement is, however, significantly different. We will explore this difference in this lesson.

The syntax of the switch statement is given as under:
switch (expression)
{
   case constant-expression:
   statements
   jump statement
   [default:
      statements
      jump statement
   ]
}
Kindly pay attention to the following:
  • The constant-expression can be an integral or string expression.
  • Control does not fall through.
  • Jump statement is required for each block – even in the default block.
  • If you need fall through behavior, youu could use the C# goto statement, as shown in the following example:

    switch(a){
    case 2:	
       Console.WriteLine("a>1 and ");
       goto case 1;
    case 1:
       Console.WriteLine("a>0");
       break;
    default:
       Console.WriteLine("a is not set");
       break;
    }

As mentioned earlier, we can also use a string in the switch constant-expression. This is demonstrated with the help of the following example:
void func(string option){ 
   switch (option) 
   { 
   case "label": 
      goto case "jump": 
   case "quit": 
      return; 
   case "jump": 
   case "unwind": 
      throw new Exception(); 
   default: 
      break; 
   } 
}

Next >>> Lesson No. 9: C# Properties







Home - Advertise - Contact - Disclaimer - About Us
© Since 2006 pickatutorial.com -- All Rights Reserved.