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