Static members belong to the class itself, not to any instance. They are shared across all objects of that class.
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
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
// 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 ...