Thomas
Thomas

Reputation: 2984

Variable does not exist in current context although it does exist

I'm running unittests for a dll.

[TestMethod]
public void Test1()
{
    List<MyObject> a = GetData();
}

That works fine BUT when I tried to change it to the following:

[TestMethod]
public void Test1()
{
    List<MyObject> b = GetData();
    List<MyObject> a = GetData();
}

I got the problem that when I reach the breakpoint on b or a it says b is not existing in the current context. BUT the same line works for a collegue of mine.

I already restarted visual studio and cleaned the solution and rebuilt it. Does anyone have an idea there?

Upvotes: 2

Views: 1153

Answers (1)

tolanj
tolanj

Reputation: 3724

This will happen if you are debugging a version compiled in release mode / with the 'Optimise Code' flag set.

This is because the compiler is then free to take variables out of scope if it knows they can never be used, where as Debug mode will retain variables in scope as long as they are in-scope from a language perspective.

Since b (and a) are never used in you code the compiler is free, in release mode to treat your code as:

[TestMethod]
public void Test1()
{
    GetData();
    GetData();
}

Which indeed it does.

Upvotes: 3

Related Questions