Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Main() doesn't want to access a class variable

Why I can access to X variable from "method()" and not from Main() method?

    class Program
    {
        int X;  // this is the variable I want access

        static void Main(string[] args)
        {
            int a;
            a = X; // this doesnt work, but why?
        }
        void metodo()
        {
            int b;
            b = X; //this works, but why?
        }
    }
like image 307
user396808 Avatar asked Nov 28 '22 18:11

user396808


2 Answers

Try

static int X

X is an instance variable, which means that each and every instance of your class will have their own version of X. Main however, is a static method, which means, that there is only one Main for all instances of the Program class, so it makes no sense for it to access X, since there might be multiple X's or there might be none at all, if no Program instances are created.

Making X itself static, means that all Program instances will share X, so the shared method will be able to access it.

like image 54
SWeko Avatar answered Dec 16 '22 05:12

SWeko


Main() is a static function. Non-static variables cannot be accessed from static functions.

like image 40
MikeP Avatar answered Dec 16 '22 04:12

MikeP