Archive

Posts Tagged ‘Scope’

Suggestion: Define scoped variable at C# switch conditional statement

Trying to reuse the conditional value of a switch statment in C# at the fallback “default” code block of it, and looking up if that was supported in C#, I found a related discussion at:
http://stackoverflow.com/questions/29628507/c-sharp-get-switch-value-if-in-default-case

I added a comment there and also elaborated it a bit more at a suggestion (PLEASE VOTE IT UP IF YOU AGREE) to Microsoft’s Visual Studio team for the C# language:
https://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/9578766-define-variable-in-switch

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()) //SUGGESTION FOR FUTURE C# SYNTAX
{
  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

%d bloggers like this: