C#
dictionary
static class
programming
coding tutorials

Declare a dictionary inside a static class

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Yes, you can declare a dictionary inside a static class in C#. A static class is often a reasonable place to hold application-wide lookup data, constants with structure, or cached mappings that do not belong to any instance.

The real design question is not whether it is allowed, but how the dictionary should be initialized, exposed, and protected from unsafe mutation. A static dictionary is shared by the whole process, so write access needs more thought than read access.

Basic Static Dictionary Declaration

The simplest form is a static readonly field:

csharp
1using System.Collections.Generic;
2
3public static class ErrorCodes
4{
5    public static readonly Dictionary<int, string> Messages = new()
6    {
7        [404] = "Not Found",
8        [500] = "Internal Server Error",
9        [503] = "Service Unavailable"
10    };
11}

You can read it anywhere:

csharp
string message = ErrorCodes.Messages[404];
Console.WriteLine(message);

readonly means the field reference cannot be replaced after initialization. It does not mean the dictionary contents are immutable.

Prefer a Property or Read-Only View

If callers should not modify the dictionary, do not expose the mutable object directly. A safer pattern is to keep the dictionary private and expose only read operations.

csharp
1using System.Collections.Generic;
2
3public static class CountryCodes
4{
5    private static readonly Dictionary<string, string> _codes = new()
6    {
7        ["CA"] = "Canada",
8        ["US"] = "United States",
9        ["JP"] = "Japan"
10    };
11
12    public static bool TryGetName(string code, out string name) =>
13        _codes.TryGetValue(code, out name);
14}

This preserves control over the data structure and prevents accidental writes from unrelated parts of the application.

Initialize in a Static Constructor When Setup Is Non-Trivial

If the dictionary requires logic during startup, use a static constructor:

csharp
1using System.Collections.Generic;
2
3public static class MimeTypes
4{
5    private static readonly Dictionary<string, string> _types;
6
7    static MimeTypes()
8    {
9        _types = new Dictionary<string, string>(System.StringComparer.OrdinalIgnoreCase)
10        {
11            [".json"] = "application/json",
12            [".txt"] = "text/plain",
13            [".xml"] = "application/xml"
14        };
15    }
16
17    public static string? Get(string extension) =>
18        _types.TryGetValue(extension, out var value) ? value : null;
19}

The runtime guarantees the static constructor runs once before first use, which makes it a clean place for one-time initialization.

Consider Thread Safety for Writes

A plain Dictionary<TKey, TValue> is safe for concurrent reads only if no thread is modifying it. If your static class updates entries at runtime, use locking or choose ConcurrentDictionary<TKey, TValue>.

csharp
1using System.Collections.Concurrent;
2
3public static class SessionCache
4{
5    private static readonly ConcurrentDictionary<string, int> _counts = new();
6
7    public static int Increment(string key)
8    {
9        return _counts.AddOrUpdate(key, 1, (_, current) => current + 1);
10    }
11}

This matters because static state is effectively global state. Once multiple threads touch it, unsafe mutations can crash or corrupt behavior in hard-to-debug ways.

When a Static Dictionary Is a Good Fit

A static dictionary works well when:

  • the mapping is application-wide
  • the lifetime should match the process lifetime
  • the data is small and cheap to keep in memory
  • the values are lookup-oriented rather than domain entities

If the data is request-specific, user-specific, or expensive to keep forever, a service or cache abstraction is usually a better design than a static class.

Common Pitfalls

  • Assuming readonly makes the dictionary immutable. It only freezes the field reference.
  • Exposing the mutable dictionary publicly when callers should only read from it.
  • Using Dictionary<TKey, TValue> for concurrent writes. Use locking or ConcurrentDictionary.
  • Turning a static dictionary into an unstructured global variable store. Keep the purpose narrow and explicit.
  • Forgetting to choose an appropriate comparer for keys such as case-insensitive file extensions.

Summary

  • You can declare a dictionary inside a static class without any special syntax.
  • Use private static readonly when you want controlled access.
  • Prefer helper methods or read-only exposure over a public mutable field.
  • Use a static constructor when initialization needs logic.
  • For concurrent writes, switch to ConcurrentDictionary or add synchronization.

Course illustration
Course illustration

All Rights Reserved.