Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern Matching Enhancement: Switch Pattern

Just had a look at the "new" C# 8.0 Features

So I tried to rewrite the following code

    private static void RunExample(ExampleCode exampleCode)
    {
        switch(exampleCode)
        {
            case ExampleCode.DefaultInterfaceMethod:
                RunDefaultInterfaceMethodExample();
                break;
            case ExampleCode.PatternMatchingEnhancements:
                RunPatternMatchingEnhancementsExample();
                break;
        }      
    }

to this:

    private static void RunExample(ExampleCode exampleCode)
    {
        exampleCode switch
        {
            ExampleCode.DefaultInterfaceMethod => RunDefaultInterfaceMethodExample(),
            ExampleCode.PatternMatchingEnhancements => RunPatternMatchingEnhancementsExample()
        };           
    }

However, I am getting the following compile error:

Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement.

Compile Error

How can I rewrite this in the new syntax?

like image 761
Fabian Bigler Avatar asked Nov 29 '25 22:11

Fabian Bigler


1 Answers

As pointed in the comments the new switch based pattern matching is expecting result to be returned.

In F# because everything is an expression, the void type is actually a valid return type for an expression and this would have worked.

In case like yours i think it is best to use the old code, but if you really want to use the new syntax you can do something like this:

Action methodToExecute = exampleCode switch
{
  ExampleCode.DefaultInterfaceMethod => RunDefaultInterfaceMethodExample,
  ExampleCode.PatternMatchingEnhancements => RunPatternMatchingEnhancementsExample,
  _ => throw new NotImplementedException()
};     
methodToExecute();

(this will work only if the methods you are executing for each case have the same definitions)

It is good practice to use exhaustive pattern, this is why i am using the last case with the underscore. In C# enum values are compiled to integers and even if your switch handles all enum labels the compiler still does not know you have handled all cases and when you add new label to the enum you won't have proper warrning that you are have unhandled case.

Whenever you are using enums it is best to use default case where all unhandled cases will fall in.

like image 89
vasil oreshenski Avatar answered Dec 08 '25 08:12

vasil oreshenski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!