Skip to content
Tutorials Center
My learning

Topics

Lesson 57 of 182 ยท Classes and Objects

Static Members and Static Classes

Understand C# static fields, methods, properties and classes - when shared state makes sense, extension method classes, the singleton pattern, and why global state hurts testing and dependency injection.

Most of what you have written in this chapter belongs to objects: each Dog has its own name, each BankAccount its own balance. But some things belong to the idea of a class as a whole. How many dogs have been created? What is the conversion factor between miles and kilometres? Those facts do not depend on any single object, so C# lets you attach them to the type itself with the keyword static.

Static members are simple to write and dangerously easy to overuse. In this lesson you will learn the syntax, the exact rules (such as why a static method cannot use instance fields), where static code is the right tool (math helpers, factories, extension methods), and why global mutable state, including the famous singleton, tends to cause pain as programs grow.

Static fields: one copy for everyone

An instance field exists once per object. A static field exists once per type, no matter how many objects you create (even zero). You access it through the type name.

C# A static counter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Issued is read as Ticket.Issued, never as a.Issued (the compiler rejects that with error CS0176). Static fields are initialized before first use of the type, and each running program has exactly one copy.

Static methods and the "no this" rule

A static method belongs to the type and is called through the type name: Math.Max(3, 5), int.Parse("42"), Path.Combine(...). Because it is not called on an object, it has no this, so it cannot touch instance fields or call instance methods directly. It can use only static members and whatever you pass as arguments.

C# Static methods and instance access

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The reverse is allowed: instance methods may call static ones. A static method that needs an object takes it as a parameter (static string Describe(Dog dog)), which is exactly what extension methods automate.

Static methods are a great fit for pure functions: ones whose result depends only on their inputs and that change nothing. They are easy to test and need no setup.

Static properties and constants

Properties can be static too, which is handy for computed shared values. Do not confuse static with const:

  • A const is a compile-time constant. The value is baked into the code that uses it. Only simple types, and implicitly static.
  • A static readonly field is set once at runtime (in an initializer or static constructor) and can hold any type, even objects.
C# const, static readonly and static properties

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

If you change a const in a library, programs compiled against the old library keep the old value until they are recompiled. For values that might change, use static readonly.

Static classes

A class declared static can contain only static members, cannot be instantiated and cannot be inherited. It is a named bag of related functions. The .NET library is full of them: Math, Console, File, Path, Enumerable.

C# A static utility class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Use a static class when you have stateless helpers that do not belong to any one data type. Resist the temptation to dump everything into a giant Utils or Helpers class. Group by purpose (TextTools, DateMath) so people can find things.

Static constructors, briefly

A static class or a normal class can have a static constructor to initialize static fields that need more than a one-line initializer. It runs once, automatically, before first use. The earlier lesson Constructors and Object Initialization shows the timing; keep them short, because an exception inside one makes the type unusable for the rest of the program.

Extension methods: static methods that look like instance methods

An extension method is a static method in a static class whose first parameter is marked this. It lets you call text.Shorten(20) as if string had that method, even though you cannot edit string.

C# An extension method

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

All LINQ methods (Where, Select, OrderBy) are extension methods on IEnumerable<T>. They are covered fully in Extension Methods.

The singleton pattern, and why you usually do not want it

A singleton is a class that allows exactly one instance, reachable from anywhere. The classic C# version combines a private constructor with a static property. Here is a safe one using Lazy<T>:

C# A singleton with Lazy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Lazy<T> creates the object on first use and is thread-safe by default. That fixes the implementation problems. The design problems remain:

  • Hidden dependencies. A method that quietly reads AppSettings.Instance has a dependency that is invisible in its signature. You cannot see what it needs without reading the body.
  • Hard to test. Tests share the one instance, so state leaks between tests, and you cannot substitute a fake.
  • Hidden coupling and ordering. Any code can change the state at any time, and bugs depend on who ran first.
  • Concurrency. Shared mutable state needs locking everywhere it is touched.

The modern alternative is dependency injection (DI): create one instance and pass it to the code that needs it, usually via the constructor (primary constructors make that short). The DI container can still guarantee a single instance (a "singleton lifetime") without the global access point. See Dependency Injection.

C# The same idea, injected

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The dependencies are explicit, tests can substitute anything, and there is still only one Settings object in the real program.

The cost of global state

Static mutable fields are global variables with a nicer name. Before adding one, ask:

  1. Who can change it? If the answer is "everyone", every bug could be anywhere.
  2. Is it thread-safe? Count++ on a static field from two threads loses updates. Use Interlocked.Increment or a lock.
  3. Does it keep objects alive? A static list that collects objects holds them forever, because the garbage collector sees the static as a root. This is a classic memory leak.
  4. Can I test it? Each test inherits what earlier tests left behind.

Acceptable statics are: constants, static readonly immutable data, pure helper functions, factory methods, and extension methods. Be suspicious of everything else.

Common mistakes

  • Accessing a static member through an instance (a.Issued). Use the type name.
  • Using this or instance fields in a static method. Pass the object as a parameter.
  • A static list that grows forever. That is a memory leak.
  • Static classes with hidden state. If the class stores data and changes it, you wanted an instance, ideally injected.
  • Calling static helpers that read the clock, files or the network inside business logic. They make the code untestable; inject an abstraction (an IClock, a file service) instead.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How many copies of a static field exist when you create 1,000 objects of the class?

    A static field belongs to the type, so there is a single copy shared by all instances.
  2. 2. Why can't a static method read an instance field directly?

    A static method runs without an object, so it cannot know which object's field you mean. Pass the object in as a parameter.
  3. 3. Which describes a static class?

    Static classes are containers of static members; the compiler forbids creating instances or deriving from them.
  4. 4. What is the main design problem with a singleton accessed as AppSettings.Instance everywhere?

    Global access points hide what code depends on and let tests leak state into each other. Injecting the instance keeps the dependency explicit.
  5. 5. What makes a method an extension method?

    The this modifier on the first parameter lets the method be called with instance syntax on that type.

Summary

  • static members belong to the type, not to an object; access them as TypeName.Member.
  • Static methods have no this; they use only static members and their parameters.
  • const values are compile-time constants; static readonly is set once at runtime and can hold objects.
  • Static classes group stateless helpers; extension methods are static methods called with instance syntax.
  • Singletons and mutable statics are global state: hidden dependencies, test leakage, thread-safety and memory-leak risks.
  • Prefer dependency injection, passing one shared instance explicitly.

Next: Access Modifiers and Encapsulation