Fall through in pattern matching
Asked Answered
F

1

15

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?

Fatshan answered 16/9, 2017 at 14:33 Comment(0)
F
14

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.

Fatshan answered 16/9, 2017 at 14:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.