To understand the reason why you'd first have to understand the difference between a class
and an actual object
.
I can define a class like the following:
public class Car
{
public string Brand {get; set;}
}
What i will be telling the compiler by this is what a Car
would look like if i where to create such a thing. No Car
is created at this point but the computer has an understanding of what a car is. We have given it a blueprint. This is called a class
Next i can go and actually create a car:
Car myCar = new Car();
myCar.Brand = "Ford";
Car otherCar = new Car();
otherCar.Brand = "BMW";
Now myCar
contains an actual object
and i told the computer it is a car. I also created another car in otherCar
. These are both individual objects. and both have their own Name
belonging to the object.
So now we have 2 objects but still only 1 class.
Now sometimes the need may arise for properties
of methods
that have some link to the concept Car
but don't require a specific Car
to work on. in C# we can define such members using the static
keyword.
We can add the following method
to our class:
public static Car GetFirstCarEverBuild();
To actually find the first car that was ever build we do not need access to a specific car. we will try to find a car here but we don't start out with one. so we mark it static
. this also means that we have to access to Brand
of the car since we have no object
to get it from. The case might even be that no Car
at all was ever created in wich case the method can just return Null
. No car has ever existed and you don't need one to find that out.
the same goes for static fields and properties:
public static Car firstCar;
This field can store 1 car and 1 only. no matter how many cars you create. it's value is tied to the class and not the object. So if myCar
will store a value in this field then otherCar
can read this same value.
Consider the following example to sum it all up:
public class Car
{
public static Car firstCar;
public Car()
{
if (firstCar == null)
firstCar = this;
}
public string Brand {get; set;}
public static Car GetFirstCarEverBuild()
{
return firstCar;
}
}