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
Xis an instance variable, which means that each and every instance of your class will have their own version ofX. Main however, is a static method, which means, that there is only one Main for all instances of theProgramclass, so it makes no sense for it to accessX, since there might be multiple X’s or there might be none at all, if noPrograminstances are created.Making X itself static, means that all
Programinstances will shareX, so the shared method will be able to access it.