The
static
keyword is a special thing in C#, it says that "regardless of how many instances of this class there are, there is only ever one of these"
It's like a physical constant in maths: there is one and only one value of Pi - but you can use it in as many equations and calculations as you like. Pi is a static value in the class of calculations.
Instances are different: think about cars. This is my car, that it your car. Over there is that car, this car is blue, that car is red, my car is black. We know that when we discuss "my car" we are talking about a specific car: and we do not expect to put your mobile in the glove box of "your car" and then retrieve it from the glove box of "my car". We are aware that each car is a separate instance of a vehicle in the class of Cars. We we also all know that you can't ask "what colour is a car?" because not all cars are the same colour. Colour is an attribute of a specific instance of a car, so to access it we need to specify exactly which car we are talking about. But ... all cars have four wheels (or they wouldn't be a car) so "how many wheels has a car?" is a valid question.
Colour is an instance question; WheelsCount is a static question
Classes in C# work the same: instance data requires an instance of the class, static data doesn't.
When the system runs the app, it needs to start executing somewhere - so it looks for the static Main method. If it wasn't static there could be dozens of them, and it would need an instance in order to run, but you can't create an instance before the program runs!
So Main is static - and as a result it doesn't have an instance associated with it - so it can't access instance variables because it doesn't know if it's supposed to use "this instance" or "that instance".
You can let Main access it in two ways:
1) Make x1 static:
class A
{
private static double x1;
private double x2;
public static void Main()
{
x1 = 100;
Console.WriteLine (x1);
}
}
Or
2) Create an instance of your class:
class A
{
private double x1, x2;
public static void Main()
{
A a = new (A);
A.x1 = 100;
Console.WriteLine (A.x1);
}
}
Make sense?