Wednesday, November 11, 2015

braces in a case

This blob of C# can't compile! There is a conflict between the two variables named: "thirteen"

using System.Web.Mvc;
namespace WebApplication.Controllers
{
   public class HomeController : Controller
   {
      public ActionResult Index(string id)
      {
         int model = 0;
         switch (id)
         {
            case "foo":
               int thirteen = 13;
               model = thirteen * 42;
               break;
            case "bar":
               string thirteen = "thirteen";
               model = thirteen.Length * 42;
               break;
         }
         return View(model);
      }
   }
}

 
 

Here is a way to solve the problem...

using System.Web.Mvc;
namespace WebApplication.Controllers
{
   public class HomeController : Controller
   {
      public ActionResult Index(string id)
      {
         int model = 0;
         switch (id)
         {
            case "foo":
            {
               int thirteen = 13;
               model = thirteen * 42;
            }
               break;
            case "bar":
            {
               string thirteen = "thirteen";
               model = thirteen.Length * 42;
            }
               break;
         }
         return View(model);
      }
   }
}

No comments:

Post a Comment