C# Static Members
The static keyword makes a member belong to the class itself rather than to any individual object. Static fields are shared across all instances, and static methods can be called without creating an object.
Static members are useful for utility functions (like Math.Sqrt) or data that should be shared across all instances, like a counter tracking how many objects have been created.
static type field;
static returnType Method() { }Static fields
A static field is shared by all instances of a class. Changing it through one object affects the value seen by all others, since there's only one copy in memory.
Static methods and classes
A static method belongs to the class and is called using the class name, not an object, like `Math.Sqrt(9)`. An entire class can be marked static if it should never be instantiated, like a utility class.
using System;
class Counter {
public static int count = 0;
public Counter() {
count++;
}
}
class Program {
static void Main() {
new Counter();
new Counter();
Console.WriteLine(Counter.count);
}
}2count is static, so it's shared across all Counter objects and increments with each new instance.
using System;
class MathHelper {
public static int Square(int n) {
return n * n;
}
}
class Program {
static void Main() {
Console.WriteLine(MathHelper.Square(5));
}
}25Square() is called directly on the class without creating a MathHelper object.
Key points
- static members belong to the class, not to individual objects.
- Static fields are shared across all instances of the class.
- Static methods are called using the class name, not an object reference.
- A static class cannot be instantiated with `new`.
