C# Switch expressions

C# 8 brings several good features, one of them is switch expressions. In the previous version I took advantage of using Switch statements with patterns. On C# 7x patterns were introduced into switch statements, which added a powerful tool for those who understood how to apply it. Never the less, looks like “they” saw this pain and made the next iteration which is Switch Expressions.

In Switch expressions all cases are expressions. Yes, we are using this little guy “=>”. with any more talk let’s take a look to one example of using the new feature.

var area = figure switch
{
    Line _ => 0, 
    Rectangle r => r.Width * r.Height,
    Circle c => Math.PI * c.Radius * c.Radius,
    _   => throw new UnknownFigureException(figure)
}; 

In the example above, we are saying the following. Is figure a Line return 0, Is figure a Rectangle return the result of the operation. Is figure a Circle return the result of the operation.

I haven’t confirmed yet but I’m pretty sure we are going to be able to do something like this

var area = figure switch
{
    Line _ => 0, 
    Rectangle r => CalcArea,
    Circle c => CalcRadius,
    _   => throw new UnknownFigureException(figure)
}; 

Where CalcArea and CalcRadius are methods that have a more robust execution.

In conclusion, Switch expressions will bring a lot of fun for developers like me and of course more productivity. Looking forward to use this feature.

Spread the word
  • Yum