Powered by Blogger.

Saturday, February 15, 2014

Switch Statement Rules in c#.net

Here in this article, we will discuss what are the rules we need to follow while writing a switch case.

You can also check my previous article on:

- How to Count number of times website visited and online users in asp.net using C#.net?

- Validation of viewstate MAC failed error in Asp.Net

- How to create drop down menu for login and signup using jQuery in asp.net?

The switch statement is very useful, but unfortunately, you can’t always use it when you may
like to. Any switch statement you write must follow to the following rules:

- You can use switch only on primitive data types, such as int or string. With any other
types (including float and double), you’ll have to use an if statement.

- The case labels must be constant expressions, such as 42 or “42”. If you need to calculate your case label values at run time, you must use an if statement.

- The case labels must be unique expressions. In other words, two case labels cannot have the same value.

- You can specify that you want to run the same statements for more than one value by
providing a list of case labels and no intervening statements, in which case the code for the final label in the list is executed for all cases in that list. However, if a label has one or more associated statements, execution cannot fall through to subsequent labels, and the compiler generates an error.

For example:

switch (xyz)
            case hey:
            case bye:
                color = "Red";
            case Clubs:
                color = "Black";
            case Spades:
                color = "Black";