C# Static
Static Members
You have already used methods like Math.Max() and Math.Sqrt(). You call them on the class name (Math), without creating an object first:
Example
Console.WriteLine(Math.Max(5, 10)); // 10
Console.WriteLine(Math.Sqrt(64)); // 8
This works because these methods are static. A static member belongs to the class itself, not to an object of the class.
The same is true for Console.WriteLine(), and for the static methods you created in the Methods chapter.
Static Fields
A normal field belongs to each object. In the example below, every Car object has its own model.
A static field belongs to the class. There is only one copy of it, and all objects share it. This is useful for counting how many cars were created:
Example
class Car
{
public string model;
public static int count = 0;
public Car(string model)
{
this.model = model;
count++;
}
}
class Program
{
static void Main(string[] args)
{
Car car1 = new Car("Volvo");
Car car2 = new Car("BMW");
Car car3 = new Car("Ford");
Console.WriteLine(car1.model + ", " + car2.model + ", " + car3.model);
Console.WriteLine("Cars created: " + Car.count);
}
}
Each car has its own model, but all cars share the same count. The constructor adds 1 to count each time a new car is created.
To use a static field, write the class name: Car.count, not car1.count.
Static Methods
A static method also belongs to the class. You call it with the class name, without creating an object, just like Math.Max():
Example
class Calculator
{
public static int Add(int a, int b)
{
return a + b;
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Calculator.Add(5, 3)); // 8
}
}
Inside its own class, you can call a static method without the class name. That is what you did in the Methods chapter, where MyMethod() and Main() were both static methods in the Program class.
A static method cannot use normal (non-static) fields. It does not belong to any object, so it does not know which car's model to use:
Example
class Car
{
public string model = "Volvo";
public static void ShowModel()
{
Console.WriteLine(model); // Error
}
}
class Program
{
static void Main(string[] args)
{
Car.ShowModel();
}
}
The compiler shows an error like this:
prog.cs(11,25): error CS0120: An object reference is required to access non-static member `MyApplication.Car.model'
To use model, remove static from the method, and call it on an object, like myCar.ShowModel().
Static Classes
A whole class can also be static, like Math. A static class can only have static members, and you cannot create objects from it: new Math() gives an error.