Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to access the top-level statement variable in a class in C#?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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, also note that actual generated class/method names can depend on the framework version, cause in .NET 6 the generational pattern changed to support unit tests in minimal hosting model):

[CompilerGenerated]
internal class Program
{
    private static void <Main>$(string[] args)
    {
        int num = 0;
    }
}

namespace ConsoleApp1
{
    internal class Program
    {
        public void TestMethod()
        {
        }
    }
}

More info about the generation patterns can be found in the docs.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading