views:

80

answers:

6

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?
        }
    }
+6  A: 

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.

SWeko
+4  A: 

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

MikeP
+1  A: 

X is an instance variable, but Main is a static method, i.e. it's not associated with any particular instance of class Program.

Oli Charlesworth
+3  A: 

Both X and metodo() are at the instance level. Main() is at the static level. If you want X to be available for both Main() and metodo you would need to declare it as static (i.e. private static int X).

Jerod Houghtelling
A: 

To have access to X you need either mark it by static keyword or create instance of Program class:

1.

static int X

2.

static void Main(string[] args)
        {
            int a;
            var program = new Program();
            a = program.X; 
        }

You should read more on class's members and on members of the class's instance.

Eugene Cheverda
+3  A: 

Pretend you have a Person class with two variables:

  • eye colour
  • number of eyes

The number of eyes belongs to the class (static) while the eye colour belongs to each instance.

If you change the number of eyes from 2 to 3 then every person in the world would instantly have 3 eyes because all of the instances share the same static variable.

If you change the eye colour of an instance of a person from blue to red then only that individual person will have red eyes.

If you were able to access non-static members inside of a static method what value would it take? Since there is no sane answer to that it is not allowed to happen.

TofuBeer