Skip to content

1.5 — static

← Roadmap · Section: 1. C# Language Fundamentals Prev: 1.4 Access modifiers · Next: 1.6 const, readonly, init, required

Markers: — · Confidence: 🔴 · Last reviewed: —


TL;DR

  • static means "this belongs to the type itself, not to any one object." There is exactly one of it, shared by everything, for as long as the program runs.
  • Static data that can change is the number one cause of two problems: memory leaks, and code you cannot test.
  • A static constructor runs once, automatically, just before the type is first used. The runtime makes sure it is safe when several threads hit it at the same time.

The concept

Normally, when you create an object, that object gets its own copy of every field. Ten objects, ten copies.

static breaks that rule. A static field has one copy, shared by every object of that type — and it exists even if you never create a single object.

A useful picture: think of a class as a blueprint for a house.

  • A normal field is like "how many bedrooms does this house have" — every house has its own answer.
  • A static field is like "how many houses have we built from this blueprint" — there is only one such number, and it belongs to the blueprint, not to any house.

That is the entire mechanism. The interesting part, and what interviews actually dig into, is what goes wrong because of it.


How it works

Static fields and methods

public class Counter
{
    private static int _total;   // ONE of these, shared by all Counters
    private int _mine;           // each Counter gets its own

    public Counter()
    {
        _total++;   // goes up every single time anyone creates a Counter
        _mine++;    // always ends up as 1 for each object
    }
}

new Counter();
new Counter();
new Counter();
// _total is now 3.
// Each object's _mine is 1.

A static method can only touch static data directly. That is because there is no specific object for it to work on — there is no this.

Static classes

A static class cannot be created with new, cannot be inherited from, and every member inside it must be static. The compiler enforces all of this.

You use it for pure helper functions — things that take input, return output, and remember nothing in between. Math, Console and File are all static classes.

public static class TemperatureConverter
{
    public static double ToFahrenheit(double celsius) => celsius * 9 / 5 + 32;
}

// Called on the type, never on an object:
var f = TemperatureConverter.ToFahrenheit(20);

Static constructors

A static constructor sets up static data. It looks like a normal constructor but with no access modifier and no parameters:

public class Config
{
    public static readonly string Version;

    static Config()          // note: no 'public', no parameters
    {
        Version = LoadVersion();
    }
}

The rules that get asked about:

  • It runs once per program run, never again.
  • It runs automatically, just before the first time anything touches the type — either creating an object or reading a static member.
  • You cannot call it, and you cannot control exactly when it runs. You only get the guarantee that it happens before first use.
  • The runtime makes it thread-safe. If two threads touch the type at the same moment, one runs the constructor while the other waits.

And here is the dangerous part. If a static constructor throws an exception, the type is permanently broken for the rest of the program. Every later attempt to use it throws a TypeInitializationException — including the very first one. Even worse, the real error is hidden one level down inside InnerException, so the message you see does not tell you what actually happened.

The practical lesson: keep static constructors boring. No file reading, no network calls, no configuration loading — nothing that can fail.

Static local functions

A local function is a small function declared inside another method. Adding static to it stops it from using variables from the method around it:

int Compute(int x)
{
    int notAllowed = 10;

    return Helper(x);

    static int Helper(int n) => n * 2;
    // Because this is 'static', it CANNOT touch 'notAllowed'.
    // If you try, the compiler stops you.
}

Why bother? Two reasons. It makes it obvious that the helper does not depend on anything around it. And it avoids allocating a hidden object to carry those captured variables — see 1.13. It is a small, free win, so it is worth making static your default for local functions.


Code

Here is a good use and a bad use, side by side.

// GOOD: no data stored, just a calculation
public static class Slug
{
    public static string From(string title) =>
        string.Join('-', title.ToLowerInvariant().Split(' '));
}
// DANGEROUS: static data that changes
public static class Cache
{
    private static readonly Dictionary<string, User> _users = new();

    public static void Add(User u) => _users[u.Id] = u;
}

That second one has three separate problems. Being able to list them all is a very good answer if an interviewer shows you code like this:

  1. It is not thread-safe. A plain Dictionary cannot handle two threads writing at once. In a web application, requests run at the same time, so this will eventually corrupt the dictionary or hang a thread in an infinite loop.
  2. Nothing is ever removed. It only grows. That is a memory leak by design — the program will slowly eat memory until it dies.
  3. It breaks when you run more than one server. Each server gets its own copy, so a user might see fresh data on one request and stale data on the next, depending on which machine answered.

The fixes, in order of how far you have scaled: ConcurrentDictionary for thread safety, then IMemoryCache for automatic eviction (see 19.2), then a distributed cache like Redis once you run multiple servers (see 19.3).


Interview questions

Q: What is a static constructor and when does it run?

It is a constructor that sets up static data. It takes no parameters and no access modifier, and you never call it yourself. The runtime runs it automatically, exactly once, just before the first time anything touches that type — whether that is creating an object or reading a static field. The runtime also guarantees it is thread-safe, so if two threads reach the type at the same moment, one runs it and the other waits.

Q: What happens if a static constructor throws an exception?

The type becomes permanently unusable for the rest of the program. The exception gets wrapped in a TypeInitializationException, and every later attempt to touch the type throws the same thing again. It is painful to diagnose, because the useful information is buried in InnerException and because the failure often shows up far away from the code that caused it. That is why static constructors should never do anything that can fail — no I/O, no configuration reading.

Q: Why is static state a problem in an ASP.NET Core application?

Three reasons. It is shared across every request, and requests run concurrently, so any static data that changes needs proper thread safety. It lives for the whole life of the process, so anything it holds on to can never be garbage collected — that is a very common source of memory leaks. And you cannot replace it in a test, so any class that depends on it becomes hard to test on its own. Dependency injection with a singleton lifetime gives you the same "one shared instance" behaviour without any of those three problems.

Q: What does static do on a local function?

It stops the function from using variables from the method around it. That means the compiler does not have to create a hidden object to hold those variables, so you avoid an allocation. It also makes the function easier to reason about, because you can see at a glance that it only depends on its own parameters. It is worth defaulting to static whenever the local function does not need anything from outside.


Traps ⚠️

  • Static fields are shared across threads. In a web app that means shared across requests happening at the same time. Anything static that can change needs a lock or a thread-safe type.
  • Anything a static field points to can never be garbage collected. A static List that only ever gets added to is a guaranteed leak. See 3.5.
  • Static makes code hard to test. You cannot swap a static call for a fake one. This is exactly why DateTime.Now scattered through a codebase makes time-based logic untestable — and why TimeProvider was added. See 20.12.
  • An exception in a static constructor kills the type forever, and hides the real error inside InnerException.
  • A static class is not the same as a singleton. A singleton is a normal object that happens to be created once. It can implement interfaces, be injected, and be replaced in tests. A static class can do none of those. Prefer a DI singleton — see 6.3.


Sources