A switch statement in C# is a great way to switch between options. It is useful if you have a few or a lot of options.
In many cases it is easier to understand that a bunch of "if-else" statements. The compiler will turn a switch statement into the equivalent of "if-else" statements, so there is no run-time penalty for using switch statements.
C# Switch Examples
Here are some very simple switch examples in C#. We'll show you how to write a correct c# switch statement for a variety of variable types.
C# Switch Int
In this case we are switching on an int value so our "case" statements need to have int values in them as well.
// temp can be any data type. In this case the compiler makes it an int
var temp = 1;
switch (temp)
{
case 1:
// do something for case 1
break;
case 2:
// do something for case 2
break;
default:
// do something for all other cases
break;
}
C# Switch String
Now we will switch on a string to see how similar it looks. Notice that you do not have to define your variable as a string. You can use the "var" keyword and the compiler will automatically figure out at compile time that you mean to use a string.
// temp can be any data type. In this case the compiler makes it a string
var temp = "MyString";
switch (temp)
{
case "MyString":
// do something for case "MyString"
break;
case "YourString":
// do something for case "YourString"
break;
default:
// do something for all other cases
break;
}
C# Switch Char
Using a C# switch statement with char variables is exactly the same as above, you just wrap your char constants in single quotes.
// temp can be any data type. In this case the compiler makes it a char
var temp = 'a';
switch (temp)
{
case 'a':
// do something for case 1
break;
case 'b':
// do something for case 2
break;
default:
// do something for all other cases
break;
}
C# Switch Default
Notice that in both of the examples above we have a case called "default". This is the case that will run if none of the cases above apply. You do not have to have a default case. If you leave the default case off and none of your cases apply then the entire block will be jumped over. Sometimes it makes a lot of sense to use the default block to trap unexpected errors. In this case you can either handle the error right there in the default block, raise an error with "throw", or simply log it to an error log.