I suggest you ...

define variable in switch

Please see the discussion at
http://stackoverflow.com/questions/29628507/c-sharp-get-switch-value-if-in-default-case

Wouldn't it be nicer if you could do the following so that fooResult is only visible in the scope of the switch block and then be able to use it at the "default" (fallback case) subblock of the switch code block?

switch (var fooResult = MyFoo())
{
case 0:
...
break;
...
default:
handleOthersCase(fooResult);
break;
}

The alternative of evaluating a 2nd time the value inside the "default" is not optimal and the other alternative of defining a local variable outside of the switch block is also not optimal for garbage collection, code optimization, is prone to code errors by accidentally using that value later on after the switch block instead of using some other variable (mistyping the name) etc. It is better practice to allow one to limit the scope of such variables to only where they're used

a workaround for protecting the local variable from accidental use later on in a long method is to do

{
var fooResult = MyFoo();
switch (fooResult)
{
case 0:
...
break;
...
default:
handleOthersCase(fooResult);
break;
}
}

that is add an extra {...} outside the var and the switch statements, but it doesn't look pretty

4 votes
Vote
Sign in
Check!
(thinking…)
Reset
or sign in with
  • facebook
  • google
    Password icon
    Signed in as (Sign out)
    You have left! (?) (thinking…)
    birbilis shared this idea  ·   ·  Flag idea as inappropriate…  ·  Admin →

    1 comment

    Sign in
    Check!
    (thinking…)
    Reset
    or sign in with
    • facebook
    • google
      Password icon
      Signed in as (Sign out)
      Submitting...

      Feedback and Knowledge Base