Letβs go through static Members in C# β a very useful concept for shared data and utility methods.
π 1. What Are Static Members?
-
Static members belong to the class itself, not to any particular object.
-
They are shared across all instances of the class.
-
Can be fields, properties, methods, or even constructors.
Key Points
-
Accessed using the class name, not an object.
-
Useful for shared data or utility/helper methods.
-
Cannot access instance members directly inside a static member.
π 2. Static Fields
public class Counter
{
public static int count = 0; // Shared across all objects
public Counter()
{
count++; // Incremented every time an object is created
}
}
// Usage
Counter c1 = new Counter();
Counter c2 = new Counter();
Console.WriteLine(Counter.count); // 2
-
count
is shared by all objects ofCounter
-
Accessed via
Counter.count
, notc1.count
π 3. Static Methods
public class MathHelper
{
public static int Add(int a, int b)
{
return a + b;
}
}
// Usage
int sum = MathHelper.Add(5, 3); // 8
-
Add
is called without creating an object -
Cannot use instance fields/properties inside a static method
π 4. Static Properties
public class AppSettings
{
public static string Version { get; set; } = "1.0";
}
// Usage
Console.WriteLine(AppSettings.Version); // 1.0
AppSettings.Version = "1.1";
Console.WriteLine(AppSettings.Version); // 1.1
- Similar to static fields, but provides controlled access via get/set
π 5. Static Constructor
-
Called automatically once before the first access to the class
-
Used to initialize static fields
public class Config
{
public static string AppName;
static Config()
{
AppName = "MyApp";
Console.WriteLine("Static constructor called");
}
}
// Usage
Console.WriteLine(Config.AppName); // Static constructor called, then MyApp
π 6. Static Class
-
Cannot be instantiated
-
Can only contain static members
-
Useful for utility/helper classes
public static class Utilities
{
public static void PrintHello()
{
Console.WriteLine("Hello!");
}
}
// Usage
Utilities.PrintHello(); // Hello!
- Cannot create objects like
new Utilities()
π 7. Summary Table
Member Type | Access | Notes |
---|---|---|
Static Field | ClassName.FieldName | Shared by all instances |
Static Method | ClassName.MethodName() | Cannot access instance members |
Static Property | ClassName.PropertyName | Provides controlled access to static data |
Static Constructor | Automatically called once before first use | Initialize static fields |
Static Class | ClassName.MethodName() | Cannot instantiate, all members static |
β Tip:
-
Use static members for shared data or utility methods
-
Use instance members for object-specific data
-
Combine with readonly to make immutable shared data