0

I have this Enum:

public enum SIZE
{
    Small = 0,
    Medium = 1,
    Large = 2,
}

I would like to use a C# switch expression but I am not sure how to create the "case" statements:

App.devWidth = App.width switch
{

};

What I want to be able to do is to set the width as follows:

Small = App.width < 700;
Medium = App.width >= 700 && App.width < 1200;
Large = App.width >= 1200;

Is there a way I can put these tests for app width on the left side of the "=>" in a switch?

haldo
  • 14,512
  • 5
  • 46
  • 52
Samantha J T Star
  • 30,952
  • 84
  • 245
  • 427
  • 2
    You should use `when` keyword, as it explained in linked duplicate [c# 8 switch expression multiple cases with same result](https://stackoverflow.com/questions/56676260/c-sharp-8-switch-expression-multiple-cases-with-same-result) – Pavel Anikhouski Apr 10 '20 at 10:24

1 Answers1

1

If you're using C# 8.0, you can use when keyword like below:

App.devWidth = App.width switch
{
    var x when x >= 0   && x < 700  => SIZE.Small,
    var x when x >= 700 && x < 1200 => SIZE.Medium,
    var x when x >= 1200            => SIZE.Large,
    _   => throw new Exception("Invalid width value")   // if width < 0
};

The above code additionally checks if App.width >= 0 and throw an exception if not (not sure whether you require this, but if not, just remove it).

Online demo

haldo
  • 14,512
  • 5
  • 46
  • 52