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).
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.