C# Smart Enums: optimized
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.