I have a simple code below. I want to access the variable x
in the class Program
. As x
is a global variable, I should be able to access it, Is there a way to access the top-level variable apart from the top level?
int x = 0;
namespace ConsoleApp1
{
internal class Program
{
public void TestMethod()
{
int y = x;
}
}
}
Error message:
CS8801 Cannot use local variable or local function 'x' declared in a top-level statement in this context
Is the below only allowed? I mean to access at the top level only?
int x = 0;
int z = x; //no compilation error?
Edit: int y = global::x;
also gives compilation error
CodePudding user response:
Is the below only allowed? I mean to access at the top level only?
Yes, top-level statements actually generate a method and all declared variables are local to it. I.e. your code will be translated to something like the following (@sharplab):
[CompilerGenerated]
internal class Program
{
private static void <Main>$(string[] args)
{
int num = 0;
}
}
namespace ConsoleApp1
{
internal class Program
{
public void TestMethod()
{
}
}
}
Also note that actual generated class/method names can depend on the framework/SDK/compiler version, cause in .NET 6 the generational pattern changed, as I understand to support integration tests for ASP.NET Core with minimal hosting model.
More info about the generation patterns can be found in the docs.