Static members and static classes
Data and methods that belong to the class itself instead of to each object: static fields, methods, classes and constructors.
static is for.
Instance vs static
| Instance member | Static member | |
|---|---|---|
obj.Member | ClassName.Member | |
new | ||
this | ||
beam.Length | Math.PI, Console.WriteLine, int.Parse |
Static methods
public static class Units{ public const double MmPerInch = 25.4; public static double InchToMm(double inches) => inches * MmPerInch; public static double MmToInch(double mm) => mm / MmPerInch;} Console.WriteLine(Units.InchToMm(10)); // no object neededConsole.WriteLine(Units.MmToInch(50.8));254 2
Static classes
static can contain only static members and can’t be instantiated (new Units() is an error). Use it for groups of related helpers, like Math, Console, File or your own Units.
Static fields: shared state
public class Member{ private static int _nextId = 1; // shared by all Members public int Id { get; } public Member() { Id = _nextId++; // each new object gets the next number }} var a = new Member();var b = new Member();Console.WriteLine($"{a.Id}, {b.Id}");1, 2
const vs static readonly
public class Config{ public const int MaxLevels = 50; // compile-time constant public static readonly DateTime Started = DateTime.Now; // set once at run time}const values must be known when compiling (numbers, strings). Use static readonly for values calculated at run time, or for objects.
Static constructors
public static class SteelTable{ public static readonly Dictionary<string, double> KgPerMetre; static SteelTable() // runs once, automatically, before first use { KgPerMetre = new() { ["IPE200"] = 22.4, ["IPE300"] = 42.2 }; }}Geometry with static methods CircleArea(double r) and CylinderVolume(double r, double h) (use Math.PI). Print the volume of a pipe with radius 0.1 m and length 6 m, to 4 decimals.
Show the solution
public static class Geometry{ public static double CircleArea(double r) => Math.PI * r * r; public static double CylinderVolume(double r, double h) => CircleArea(r) * h;} Console.WriteLine(Geometry.CylinderVolume(0.1, 6).ToString("F4"));0.1885
Remember
Static members belong to the class: one copy, used via ClassName.Member.Static methods can’t use thisor instance fields.Static classes hold helpers and can’t be instantiated. Prefer constants and stateless static methods; avoid mutable static state.