2

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

Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197
  • 4
    Per the [spec](https://learn.microsoft.com/dotnet/csharp/language-reference/proposals/csharp-9.0/top-level-statements), "If any top-level statements are present in any compilation unit of the program, the meaning is as if they were combined in the block body of a `Main` method of a `Program` class in the global namespace". Your variable is therefore local to this method, meaning it can't be accessed anywhere outside of it, which would require a member. In general, top-level statements should only be considered as a simpler way of writing `Main`, and not mixed with explicit `Main`s. – Jeroen Mostert Dec 23 '22 at 11:47

1 Answers1

3

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, because 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.

halfer
  • 19,824
  • 17
  • 99
  • 186
Guru Stron
  • 102,774
  • 10
  • 95
  • 132
  • Reminder - "cause" or "cos" is not an abbreviation of "because". Please use the full word - it is more readable this way, especially to people whose first language is not English. – halfer Dec 24 '22 at 21:07