12 Feb 2024
In C#, the static keyword is used to declare members (variables, methods, properties, constructors, and events) that belong to the type itself, rather than to instances of the type. When a member is declared as static, it means there is only one instance of that member shared by all instances of the class. Here's a breakdown of how static is used for different types of members:
- Static Fields: Static fields are shared among all instances of a class. They are initialized only once, at the beginning of the execution, and are accessible without creating an instance of the class.
public class MyClass {
public static int staticField = 10;
}
Here, staticField is a static field that belongs to the MyClass type.
- Static Methods: Static methods belong to the type rather than to any instance. They can be called directly using the type name, without the need to instantiate the class.
public class MyClass {
public static void StaticMethod() {
Console.WriteLine("Static method called");
}
}
You call a static method like this: MyClass.StaticMethod();.
- Static Properties: Similar to static methods, static properties belong to the type rather than to instances. They can be accessed directly without creating an instance of the class.
public class MyClass {
private static int _staticProperty;
public static int StaticProperty {
get { return _staticProperty; }
set { _staticProperty = value; }
}
}
You access a static property like this: MyClass.StaticProperty = 10;.
- Static Constructors: A static constructor is called only once, when the class is loaded into memory. It is used to initialize any static data or to perform any actions that need to be performed once, regardless of how many instances of the class are created.
public class MyClass {
static MyClass() {
// Initialization code
}
}
Static constructors do not take any access modifiers or parameters.
Static members are commonly used for utility functions, constants, or for maintaining shared state across all instances of a class. They help in organizing code and promoting better performance when certain members are meant to be shared across all instances.