Home > Posts > Suggestion: Define scoped variable at C# switch conditional statement

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

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: