title: C# variable scopes and the "switch" statement?
body: <p>This kind of code would normally work in PHP, but since the scope is much more strict in C#, it's not.  I can't figure out a way to write this code without repeating myself.</p>
  
  <pre><code>    static double Cube()
      {
          Console.Write("Enter the side length of the cube: ");
          try
          {
              double x = Convert.ToDouble(Console.Read());
              return Math.Pow(x, 3);
          }
          catch (FormatException)
          {
              Console.WriteLine("Invalid input, please enter a number.");
              Cube();
          }
          return 1;
      }
  </code></pre>
  
  <p>..Later in Main():</p>
  
  <pre><code>            switch (choice)
              {
                  case 0:
                      return;
                  case 1:
                      double final = Cube();
                      break;
                  default:
                      Console.WriteLine("Please enter 0 or 1.");
                      Main();
                      break;
              }
              Console.WriteLine("The volume is: {0}", Convert.ToString(final));
  </code></pre>
  
  <p>The <code>Cube()</code> method works fine, but it's messy in my opinion (<code>return 1</code> at the end to make the compiler happy).  But an error comes up saying <strong>The name 'final' does not exist in the current context</strong>.  It can't find final.  So the only way to make this work that I'm seeing is to put the <code>Console.WriteLine</code> statement right after the double final = Cube().  </p>
  
  <p>I've also tried declaring <code>double final;</code> outside the switch, then just setting <code>final</code> inside each case, but that hasn't worked either.</p>
  
  <p>Thanks!</p>