Switch

The switch statement let you evaluate an expression and based on the value of that expression do a multiway branch to the approriate piece of code.

Switch statement is allso called a 'case structure'

Example

 
public enum State
{ 
    One, Two, Three, Four 
};

public class switchTest
{
    public static void DoASwitch(State mystate)
    {
        switch (mystate)
        {
            case State.One: 
                Console.WriteLine("I'm in state one!"); 
                break;
            case State.Two: 
                Console.WriteLine("I'm in state two!"); 
                break;
            case State.Three: 
                Console.WriteLine("I'm in state three!"); 
                break;
            case State.Four: 
                Console.WriteLine("I'm in state four!"); 
                break;
            default: Console.WriteLine("I'm at the default!"); break;
        }
    }
}

Switch Expression ( C#8 )

If there is value produced in each of the case blocks it then is possible the use a switch expression. Switch Expression uses less braces and no repetitive case and or break statements.

Example Switch Expression

enum County
{
    Utrecht = 0,
    Gelderland = 1,
    Flevoland = 2
}
class SwitchTest
{
    public string GetCounty(County county)
        => county switch
        {
            County.Utrecht => county.ToString(),
            County.Gelderland => county.ToString(),
            County.Flevoland => county.ToString(),
            _ => "Did not find your county"
        };
}

{{opmerking.Naam}}:

{{opmerking.OpmerkingText}}

            

Saving your comment....

Naam is verplicht!
Email is verplicht!
Opmerking is verplicht!