'C# - Get switch value if in default case

Help please, I have this case:

switch(MyFoo()){
    case 0: //...
        break;
    case 1: //...
        break;
    case 2: //...
        break;
    default:
        // <HERE>
        break;
}

As you can see the switch gets the value directly from a method without saving it as a variable.

Is it possible to get which value fires the default case? For example if MyFoo() returns 7, how can I get that value?

I want to avoid to save the method result as a variable, is there a way to get the switch value from inside a case? Something like this:

default:
    this.SwitchValue // <<--
    break;

Thank you for reading, ~Saba



Solution 1:[1]

I can't see a reason as well why to use it like that but may be a work around will be like this:

int x;
switch ( x = MyFoo())
{
    case 0: //...
        break;
    case 1: //...
        break;
    case 2: //...
        break;
    default:
        var s = x; // Access and play with x here
        break;
}

Solution 2:[2]

No, this isn't possible. You can assign the value to variable inside switch, if you want to look like reinventing the wheel:

        int b;
        .....
        switch (b = MyFoo())
        {
            case 1:
                break;
            case 2:
                break;
            default:
                //do smth with b
                break;
        }

Solution 3:[3]

The easiest way is to save the result of MyFoo() as a variable.. But if you don't want to do that you could do:

switch(MyFoo()){
    case 0: //...
        break;
    case 1: //...
        break;
    case 2: //...
        break;
    default:
        this.SwitchCase = MyFoo();
        break;
}

Although I would advise against this and say save the value as a variable to save your program the extra work.

Saving the value of MyFoo as a variable becomes more important the more complex the example gets as the value of MyFoo could have changed between the switch and default case.

Also this will only work where MyFoo has no side-effects and obviously must always return the same value for any given parameter.

for example the following would work:

Private int MyFoo()
{
   return 3;
}

But the following would not:

private int MyFoo()
{
  Random r = new Random();
  return r.Next(5);
}

Solution 4:[4]

This is possible now.

https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#property-patterns

Example:

int? TryGetColumnIndex(string columnName)
    => GetValue(columnName)
    switch
    { var result when result > -1 => result, _ => new int?() };

result will capture the result of GetValue.

Even cooler, you can do propery checks.

i.e instead of when result > -1 you can even say when result.ToString().Length > 2 and such.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Amr Elgarhy
Solution 2 Andrew
Solution 3 StayOnTarget
Solution 4 user3265356