Zalek Bloom
Zalek Bloom

Reputation: 551

The name 'test1' does not exist in the current context

In MVC controller I defined a string variable, but still I am getting message: "The name 'test1' does not exist in the current context".

Here is my code:

public ActionResult About()
{
  string test1;
  test1 = "A";
  return View();
}

I tried to put a breakpoint on all 3 statements, but it stopped only on the "return" command. Here is a picture from Visual Studio 2012 a breakpoint:

Visual Studio Breakpoint

Any ideas?

Upvotes: 2

Views: 3150

Answers (3)

fcuesta
fcuesta

Reputation: 4520

For debugging, change your build configuration to Debug instead of Release. The Release configuration can optimize your code and prevent the debugger from seeing some local variables.

Upvotes: 6

Ken White
Ken White

Reputation: 125747

You never use the variable after assigning a value to it, so the compiler is smart enough to know it's meaningless and it can discard it.

Here's what the compiler sees:

public ActionResult About()
{
  string test1;   // Declare a variable
  test1 = "A";    // Do something meaningless with it
  return View();  // Don't use it, so throw away the two previous statements
}

The compiler is smart enough to know that code that doesn't actually do anything can just be ignored. It's basic optimization - don't compile code that does nothing.

Upvotes: 3

kevintodisco
kevintodisco

Reputation: 5191

test1 was likely optimized out because you do not use it in the scope in which it's declared.

Upvotes: 0

Related Questions