简体   繁体   中英

Fall through in pattern matching

currently in c#7 (version 15.3.4) following code is valid to compile but both variables are legitimately unusable.

switch(fruit)
{
    case Apple apple:
    case Orange orange:
    // impossible to use apple or orange
    break;
    case Banana banana:
    break;
}

If you try to use them, you get familiar error, variable might not be initialized before accessing.

Some times in pattern matching you don't care about exact type, as long as that type is in category that you want. here only apples and oranges as an example.

List<Fruit> applesAndOranges = new List<Fruit>();
switch(fruit)
{
    case Fruit X when X is Apple || X is Orange:
    applesAndOranges.Add(X);
    break;
    case Banana banana:
    break;
}

Are there better approaches?

You can use discards if you don't like to make garbage local variables in current region. then you can use switched variable directly. you may need additional cast if switched variable is of super class like object or something else.

List<Fruit> applesAndOranges = new List<Fruit>();
switch(fruit)
{
    case Apple _:
    case Orange _:
    applesAndOranges.Add(fruit);
    break;
    case Banana banana:
    break;
}

I don't know how pattern matching is compiled. if it makes use of jump tables then this approach could be also a little faster. performance is not my concern though. this is more readable.

I'm already pleased by both solutions, so this is Q&A post that I liked to share.

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