⌘BABAKOV.NET Let's code!
100% [dark] [ru]

Switch Expressions - Switch Expressions - A New Feature in C# 8

Good news, now you can implement SWITCH in a new way.
Switch expressions are introduced in C# 8, which implement a shorter syntax for returning a value.

Here is the syntax of the SWITCH expression example:

static string Display(object o) => o switch
{
    Point { X: 0, Y: 0 }         => "origin",
    Point { X: var x, Y: var y } => $"({x}, {y})",
    _                            => "unknown"
};


In this example, the type pattern is first checked, and then the pattern of properties inside {curly brackets}.
The underscore "_" describes the discard pattern, similar to «default:» for switch operators.
You can complicate the example using tuples and positional, as in the following example:

static State ChangeState(State current, Transition transition, bool hasKey) =>
    (current, transition) switch
    {
        (Opened, Close)              => Closed,
        (Closed, Open)               => Opened,
        (Closed, Lock)   when hasKey => Locked,
        (Locked, Unlock) when hasKey => Closed,
        _ => throw new InvalidOperationException($"Invalid transition")
    };


We don't need to declare a variable or an explicit type for each case. Instead, the compiler itself matches the test tuple with the tuples defined for each case.

This allows us to write declarative code that fixes our intentions, instead of procedural code that implements tests for it. The compiler becomes responsible for implementing this boring procedural code.

P.S. Translated myself, as I understood, I hope the essence is conveyed correctly.
P.P.S. Thank you for your attention.

Comments (0)

No comments yet.

Leave a comment
Comment
Images (up to 5 MB)
Your comment will appear after moderation.