C# Exception Handling
C# File I/O
C# Delegates and Events
C# Generics
C# Async Programming
C# Static Members

C# Static Members

Static members belong to the class itself, not to any instance. They are shared across all objects of that class.

1 - Static Fields and Properties

public class Counter
{
    private static int _count = 0;
    public static int Count => _count;

    public Counter() => _count++;
    ~Counter() => _count--;
}

var a = new Counter();
var b = new Counter();
Console.WriteLine(Counter.Count); // 2

2 - Static Methods

public static class MathUtils
{
    public static int Clamp(int value, int min, int max) =>
        Math.Max(min, Math.Min(max, value));

    public static bool IsPrime(int n)
    {
        if (n < 2) return false;
        for (int i = 2; i <= Math.Sqrt(n); i++)
            if (n % i == 0) return false;
        return true;
    }
}

Console.WriteLine(MathUtils.Clamp(150, 0, 100)); // 100
Console.WriteLine(MathUtils.IsPrime(17));         // True

3 - Static Classes

// A static class cannot be instantiated — perfect for utility methods
public static class StringExtensions
{
    public static string Truncate(this string s, int maxLength) =>
        s.Length <= maxLength ? s : s[..maxLength] + "...";
}

string title = "A very long article title that should be shortened";
Console.WriteLine(title.Truncate(20)); // A very long article ...

Note: Static methods cannot access instance fields or methods (no this). Use them for pure utility operations or factory methods. Avoid overusing static state — it makes code harder to test and reason about.

-Tip-