C# Static Members

In C#, a static member belongs to the class itself — not to any individual object. You do not need to create an object to use a static member. You access it directly through the class name.

The Difference: Instance vs Static

┌──────────────────────────────────────────────────────────────┐
│          INSTANCE vs STATIC                                  │
├──────────────────────────────────────────────────────────────┤
│                                                              │
│  INSTANCE MEMBER:                                            │
│  Each object gets its own separate copy.                     │
│                                                              │
│  Student s1 = new Student();  s1.name = "Alice";             │
│  Student s2 = new Student();  s2.name = "Bob";               │
│  (s1.name and s2.name are different — each object has own)   │
│                                                              │
│  STATIC MEMBER:                                              │
│  All objects share one single copy owned by the class.       │
│                                                              │
│  Student.Count = 3;   (one value — the whole class owns it)  │
│                                                              │
└──────────────────────────────────────────────────────────────┘

Static Fields

A static field holds a value shared by all instances of the class. A common use is tracking how many objects have been created.

class Student
{
    public string Name;
    public static int Count = 0;   // shared by all Student objects

    public Student(string name)
    {
        Name = name;
        Count++;   // increment every time a new student is created
    }
}

class Program
{
    static void Main()
    {
        Student s1 = new Student("Alice");
        Student s2 = new Student("Bob");
        Student s3 = new Student("Carol");

        Console.WriteLine(Student.Count);   // 3
        // Access via class name, not object name
    }
}

Static Field Memory Diagram

┌─────────────────────────────────────────────────────────────┐
│                  MEMORY LAYOUT                              │
├────────────────────────┬────────────────────────────────────┤
│  Heap (object data)    │  Static memory (class data)        │
├────────────────────────┼────────────────────────────────────┤
│  s1 → Name = "Alice"   │                                    │
│  s2 → Name = "Bob"     │  Student.Count = 3                 │
│  s3 → Name = "Carol"   │  (one shared copy for all)         │
└────────────────────────┴────────────────────────────────────┘

Static Methods

A static method belongs to the class, not to an instance. You call it with the class name — no object needed. It can only access other static members of the class.

class MathHelper
{
    public static int Square(int x)
    {
        return x * x;
    }

    public static double CircleArea(double radius)
    {
        return 3.14159 * radius * radius;
    }
}

class Program
{
    static void Main()
    {
        Console.WriteLine(MathHelper.Square(5));           // 25
        Console.WriteLine(MathHelper.CircleArea(3.0));     // 28.27...
        // No MathHelper object needed
    }
}

Static Classes

A static class contains only static members and cannot be instantiated (you cannot create objects from it). It is a container for utility methods.

static class Converter
{
    public static double KgToPounds(double kg)
    {
        return kg * 2.20462;
    }

    public static double CelsiusToFahrenheit(double c)
    {
        return c * 9 / 5 + 32;
    }
}

class Program
{
    static void Main()
    {
        Console.WriteLine(Converter.KgToPounds(70));        // 154.32
        Console.WriteLine(Converter.CelsiusToFahrenheit(100)); // 212
    }
}

Rules for Static Classes

┌────────────────────────────────────────────────────────────┐
│  Static Class Rules:                                       │
│  ✅ All members must be static                             │
│  ✅ Cannot be instantiated (no new keyword)                │ 
│  ✅ Cannot be inherited                                    │
│  ✅ Cannot contain instance constructors                   │
│  ✅ Sealed by default (cannot be base class)               │
└────────────────────────────────────────────────────────────┘

Static Constructor

A static constructor runs once — the first time the class is used. It initializes static fields. You cannot call it manually or pass parameters to it.

class Config
{
    public static string AppName;
    public static int Version;

    static Config()   // static constructor — runs once automatically
    {
        AppName = "MyApp";
        Version = 1;
        Console.WriteLine("Config initialized.");
    }
}

class Program
{
    static void Main()
    {
        Console.WriteLine(Config.AppName);   // Config initialized. (first use)
        Console.WriteLine(Config.Version);   // MyApp / 1
    }
}

Static Constructor Timeline

┌──────────────────────────────────────────────────────────────┐
│  Program starts                                              │
│       │                                                      │
│       ▼                                                      │
│  First access to Config class                                │
│       │                                                      │
│       ▼                                                      │
│  Static constructor runs ONCE                                │
│       │                                                      │
│       ▼                                                      │
│  All subsequent uses of Config use already-initialized data  │
│  (static constructor never runs again)                       │
└──────────────────────────────────────────────────────────────┘

Static vs Instance — Access Rules

class Example
{
    public int instanceField = 10;        // instance
    public static int staticField = 99;   // static

    public void InstanceMethod()
    {
        Console.WriteLine(instanceField);  // ✅ OK
        Console.WriteLine(staticField);    // ✅ OK — static accessible in instance
    }

    public static void StaticMethod()
    {
        Console.WriteLine(staticField);    // ✅ OK
        // Console.WriteLine(instanceField); ❌ ERROR — no instance context
    }
}

Access Rule Summary

┌──────────────────────────┬──────────────────────────────────┐
│ From                     │ Can Access                       │
├──────────────────────────┼──────────────────────────────────┤
│ Instance method          │ Instance members + Static members│
│ Static method            │ Static members ONLY              │
└──────────────────────────┴──────────────────────────────────┘

Real Example: Singleton Pattern

Static members enable the Singleton design pattern — ensuring only one instance of a class ever exists.

class Database
{
    private static Database _instance = null;
    private static int _connectionCount = 0;

    private Database()
    {
        _connectionCount++;
        Console.WriteLine("Database connected. Connections: " + _connectionCount);
    }

    public static Database GetInstance()
    {
        if (_instance == null)
            _instance = new Database();   // creates only once
        return _instance;
    }
}

class Program
{
    static void Main()
    {
        Database db1 = Database.GetInstance();  // Database connected. Connections: 1
        Database db2 = Database.GetInstance();  // no message — returns same object
        Database db3 = Database.GetInstance();  // no message — returns same object

        Console.WriteLine(db1 == db2);  // True — same instance
    }
}

Built-In Static Classes You Already Use

┌───────────────────────────────────────────────────────────┐
│  Console.WriteLine()       → Console is a static class    │
│  Math.Sqrt(16)             → Math is a static class       │
│  Convert.ToInt32("5")      → Convert is a static class    │
│  string.IsNullOrEmpty(s)   → static method on string      │
│  Array.Sort(arr)           → static method on Array       │
└───────────────────────────────────────────────────────────┘

Quick Summary

┌─────────────────────────────────────────────────────────────┐
│  static field     → shared by all objects                   │
│  static method    → called on class, not object             │
│  static class     → cannot be instantiated, all-static      │
│  static constructor → runs once on first class use          │
│                                                             │
│  Access: ClassName.Member (not objectName.Member)           │
│  Static methods cannot access instance members              │
└─────────────────────────────────────────────────────────────┘

Static members are essential for utility functions, shared counters, configuration data, and design patterns like Singleton. Every C# program uses static members from day one — Main() itself is a static method.

Leave a Comment

Your email address will not be published. Required fields are marked *