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?
        }
    }
                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.
Main() is a static function. Non-static variables cannot be accessed from static functions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With