Tuesday 26 March 2019

Switch Expressions

I found out some days ago that Java 12 comes with switch expressions. Doing some googling it seems that C# 8 could also get them added.

The feature seems rather nice (I directly copy/paste the Java sample)

int value = switch (number) {
    case "ONE"   -> 1;
    case "TWO"   -> 2;
    case "THREE" -> 3;
};

I immediately wondered if JavaScript was planning to incorporate this feature, but some googling brought no answers. Well, giving it a second thought, the thing is that with JavaScript's clean and concise syntax we can almost the same by using a dispatch table:

let numStr = "TWO";
let num = {
        "ONE": 1,
        "TWO": 2,
        "THREE": 3
    }[numStr];

It's almost the same, just the switch condition is moved from the beginning to the end of the expression. Doing the same in C# is a bit more verbose mainly because of having to write the type:

var numStr = "TWO";
int item = new Dictionary<string, int>{
 	["ONE"]= 1,
    ["TWO"]= 2,
    ["THREE"]= 3
}[numStr];

Notice that we're using the Dictionary initializer syntax incorporated in C# 6.

By the way, I've never thought about the small performance differences between a switch statement and dispatch table, so this StackOverflow question has been a nice reading.

No comments:

Post a Comment