Answers for "C# Switch Statement VS Switch Expression"

C#
0

C# Switch Statement VS Switch Expression

// Switch Statement VS Switch Expression
static void TrafficUsingSwitchStatement(string color)
{
    string result;

    switch (color)
    {
        case "Red":
            result = "Stop!";
            break;
        case "Yellow":
            result = "Slow down!";
            break;
        case "Green":
            result = "Go!";
            break;
        default:
            result = "Invalid input!";
            break;
    }

    Console.WriteLine(result);
}

static void TrafficUsingSwitchExpression(string color)
{
    string result = color switch
    {
        "Red" => "Stop!",
        "Yellow" => "Slow down!",
        "Green" => "Go!",
        _ => "Invalid input!"
    };

    Console.WriteLine(result);
}
Posted by: Guest on July-17-2021

C# Answers by Framework

Browse Popular Code Answers by Language