You can only call a method from a class without an instance of that class if the method is declared
static
i.e. it does not need to access any instance based information in order to work.
Think of cars for a moment: a car has two properties: a colour and a number of wheels. Let's write a quick method to fetch them.
The colour of a car obviously depend on the specific car you refer to: "my car" will be black, "your car" might be blue, "that car" could be green now, and refer to a yellow car in a minute. So GetColour requires access to instance based information:
public Color GetColour()
{
return this.Colour;
}
And we need an instance of the car to use it:
Car myCar == new Mercedes("A180", Color.Black);
Car yourCar = new BMW("6 Series", Colour.Blue);
Console.WriteLine("My car is {0}", myCar.GetColour());
Console.WriteLine("Your car is {0}", yourCar.GetColour());
But the number of wheels is a constant - it's always four (because if it had two it would be a motorcycle!) So we don't need access to any instance based information, and it can be a
static
method:
public static int GetNumberOfWheels()
{
return 4;
}
And we use it without an instance by using the class name as a prefix:
Console.WriteLine("My car has {0} wheels", Car.GetNumberOfWheels());
Console.WriteLine("Your car has {0} wheels", Car.GetNumberOfWheels());
So provided X does not need to access any instance information, you can declare it as
static
and call it via the class name:
A2.X();
But if it needs to use
this
at all - explicitly or implicitly - it can't be
static
because that is the accessor for instance based information.