Static Members
Static Members
Section titled βStatic MembersβWhat it means
Section titled βWhat it meansβA static member belongs to the class itself, not to any individual instance β thereβs only ever one copy, shared across every use, and you access it through the class name rather than an object reference. Common uses: utility methods that donβt need instance state (Math.Sqrt), shared counters, and constants.
Examples
Section titled βExamplesβpublic class Counter{ public static int TotalCount; // shared across ALL instances
public Counter() { TotalCount++; // every new Counter increments the SAME shared field }}
var c1 = new Counter();var c2 = new Counter();var c3 = new Counter();Console.WriteLine(Counter.TotalCount); // 3 -- accessed via the class name, not an instance
public static class MathHelpers // an entire static class -- can't be instantiated{ public static double CelsiusToFahrenheit(double c) => c * 9 / 5 + 32;}
double f = MathHelpers.CelsiusToFahrenheit(20); // no `new` neededCommon mistake
Section titled βCommon mistakeβTrying to access an instance member from a static method (or vice versa, expecting a static fieldβs value to differ per instance) β static methods have no this and canβt see instance data, since they arenβt tied to any particular object.
public class Person{ public string Name;
public static void Greet() { Console.WriteLine($"Hello, {Name}!"); // Error: an object reference is required for the non-static field 'Name' }}
// Fix: either make the method non-static, or pass the data in explicitlypublic static void Greet(string name){ Console.WriteLine($"Hello, {name}!");}Quick practice
Section titled βQuick practiceβ-
How many copies of a
staticfield exist across all instances of a class?Answer
Exactly one, shared by every instance (and accessible even with zero instances created). -
Can a static method access an instance field directly?
Answer
No β static methods have nothisreference and aren't tied to any particular instance, so they can't see instance-level data without it being passed in explicitly. -
What does a
static class(likeMathHelpers) prevent you from doing?Answer
Creating instances of it withnewβ a static class can only contain static members and exists purely as a namespace-like container for related utility functionality.