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

  1. Accessed using the class name, not an object.

  2. Useful for shared data or utility/helper methods.

  3. 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 of Counter

  • Accessed via Counter.count, not c1.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 TypeAccessNotes
Static FieldClassName.FieldNameShared by all instances
Static MethodClassName.MethodName()Cannot access instance members
Static PropertyClassName.PropertyNameProvides controlled access to static data
Static ConstructorAutomatically called once before first useInitialize static fields
Static ClassClassName.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