The name 'temp' does not exist in the current context (C# desktop application)
-
02-06-2021 - |
Question
I am making a C# desktop application with following code:
static class ClassA
{
public static string Process()
{
string temp = Functions.Test();
return temp;
}
}
static class Functions
{
public static string Test()
{
return "ok";
}
}
Problem is the variable "temp" doesn't get any value from Test() funciton. When I try to check its value in Immediate Window, I get the message "The name 'temp' does not exist in the current context"
Both ClassA and Functions are in separate class files but belong to same namespace.
Solution
try with
static class ClassA
{
string temp = Functions.Test();
public static string Process()
{
return temp;
}
}
static class Functions
{
public static string Test()
{
return "ok";
}
}
OTHER TIPS
I know this is an older question, but hopefully this will help newer developers as well: I came across a similar issue and realized that my two classes (which are in two different projects) were targeting two different frameworks. Once I switched them to both target Net Framework 4.5 they compiled perfectly and without this issue.
The only way I can reproduce the error is by checking
? temp
in the Immediate Window when the code is not running.
If you call the actual method by
? ClassA.Process()
it works just fine.
Also, if you place a breakpoint on the return temp;
line and run your program, the Immediate Window will give the correct result when checking
? temp
when the debugger stops at you breakpoint. At this point temp
will be in the current context.
Adding the following to your code:
class Program
{
static void Main(string[] args)
{
Console.WriteLine(ClassA.Process());
Console.ReadLine();
}
}
returns "ok"
Something else is wrong with your code.