简体   繁体   中英

How can I use >= on the left of a C# switch expression?

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM