C# Smart Enums: optimized

Published: (January 1, 2026 at 09:12 PM EST)
2 min read
Source: Dev.to

Source: Dev.to

The Problem: The “LINQ Tax”

In Part 1 we replaced magic numbers with records. To find a specific status we used LINQ:

var status = Status.All.SingleOrDefault(x => x.Id == productStatusId);

While this works, it has two drawbacks:

  • Complexity – you must repeat the LINQ logic every time you need to fetch a status.
  • Performance – LINQ performs a linear search O(n). For a large set of statuses in a high‑traffic app this adds unnecessary overhead.

We can optimize this by adding a private Dictionary inside our Status class, giving us instant O(1) lookups regardless of how many statuses exist.

public record StatusValue(int Id, string Description);

public static class Status
{
    public static readonly StatusValue Pending     = new(1, "Pending Approval");
    public static readonly StatusValue Available   = new(2, "Available for Sale");
    public static readonly StatusValue OutOfStock = new(3, "Out of Stock");

    public static readonly StatusValue[] All = { Pending, Available, OutOfStock };

    private static readonly Dictionary _lookup = All.ToDictionary(s => s.Id);

    // O(1) access to the full object
    public static StatusValue? Get(int id) => _lookup.GetValueOrDefault(id);

    // Quick existence check
    public static bool Exists(int id) => _lookup.ContainsKey(id);

    // Accessing properties
    public static string GetDescription(int id) => Get(id)?.Description ?? "Unknown";
}

Usage

Instead of writing LINQ queries, services can now do:

if (Status.Exists(userInputId))
{
    var label = Status.GetDescription(userInputId);
    Console.WriteLine($"Processing: {label}");
}

Additional Resources

  • Live Demo – try it on .NET Fiddle
  • Source Code – see the GitHub Gist
  • Dictionary Class Documentation – learn more about the O(1) lookup engine in the official .NET docs.

Version Note: These performance optimizations are designed for .NET 6+ environments.

Back to Blog

Related posts

Read more »

C# Smart Enums: advanced

!Cover image for C Smart Enums: advancedhttps://media2.dev.to/dynamic/image/width=1000,height=420,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-upload...

MiniScript Road Map for 2026

2026 Outlook With 2025 coming to a close, it’s time to look ahead to 2026! MiniScript is now eight years old. Many programming languages really come into their...

Memory Subsystem Optimizations

Article URL: https://johnnysswlab.com/memory-subsystem-optimizations/ Comments URL: https://news.ycombinator.com/item?id=46456215 Points: 8 Comments: 1...