What is a static property? Give an example.
Short answer
A static property belongs to the class itself rather than to any specific instance of that class, meaning it is accessed through the class name directly and shares the exact same value across every part of the application, regardless of how many objects of that class have been…
Advertisement
AModel answer
A static property belongs to the class itself rather than to any specific instance of that class, meaning it is accessed through the class name directly and shares the exact same value across every part of the application, regardless of how many objects of that class have been created. Static properties are commonly used for values that should be shared globally, such as a counter tracking how many instances of a class have been created.
public class Counter {
private static int _count = 0;
public static int TotalCreated {
get { return _count; }
}
public Counter() { _count++; }
}
var a = new Counter();
var b = new Counter();
Console.WriteLine(Counter.TotalCreated); // 2Real-world example
A logging library uses a static property to track the total number of log entries written across the entire application, since this count needs to be shared globally rather than tracked separately for each individual logger instance.
Likely follow-ups
- Can a static property be accessed through an instance of the class instead of the class name?
- What is the difference between a static property and a static field?
Related topics