Instructions for selecting switch C#
Blog > C# > Instructions for selecting switch C#

Instructions for selecting switch C#


Instructions for selecting switch C#

The switch selection instruction (Instructions for selecting switch C#) is a multiple-choice instruction that allows you to define the code to be executed when one of the set values is reached.


The dependency of the switch statement from if

The switch statement performs a check of a series of conditions for a given variable so that it can be successfully replaced by a sequence of if statements. However, this would increase the amount of code and at the same time reduce its clarity and speed. The switch statement can not always replace the if statement string. This is due to the fact that it can check the condition only for one variable.

Switch construction

Important keywords include switch, case, break and optional default keywords. The method of their application is presented in the example below.

switch( zmienna ) // variable from the value that depends on the choice of the appropriate case
case wart_1:
    //code for a variable with a value wart_1
    break; // very important, skipping would trigger the code
    // another case, although the variable value would not have been reached.
case wart_2:
    //code for a variable with a value wart_2
    //code for a variable having a value not listed in the other case

In the case when the variable is of the bool type, it is possible to specify conditions instead of values in the case. This is the only case, because the conditions will return true or false, which corresponds to the bool value. However, there are restrictions, the value must be constant (const) and the results of checking true and false can only happen once.

bool zmienna = false;

switch( zmienna )
     case (6 < 0):

Allowed data types – Instructions for selecting switch C#

Since a single variable is checked in defined cases (case), it must have a unique integer value or a value that can be represented by an integer. Allowed types are: short, int, long, long long, and also char (which can be written as a number – ASCII character code) or enum (each element has a numerical value assigned). It is not allowed to use, for example, float and double, because due to the approximation, checking the conditions might not be unambiguous.

Any questions?