Skip to content

Static Members

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.

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` needed

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 explicitly
public static void Greet(string name)
{
Console.WriteLine($"Hello, {name}!");
}
  1. How many copies of a static field exist across all instances of a class?

    AnswerExactly one, shared by every instance (and accessible even with zero instances created).
  2. Can a static method access an instance field directly?

    AnswerNo β€” static methods have no this reference and aren't tied to any particular instance, so they can't see instance-level data without it being passed in explicitly.
  3. What does a static class (like MathHelpers) prevent you from doing?

    AnswerCreating instances of it with new β€” a static class can only contain static members and exists purely as a namespace-like container for related utility functionality.