Skip to content

Instantly share code, notes, and snippets.

@heldercsousa
Last active January 2, 2026 08:45
Show Gist options
  • Select an option

  • Save heldercsousa/40b08d467423c32c813647c4e432b36d to your computer and use it in GitHub Desktop.

Select an option

Save heldercsousa/40b08d467423c32c813647c4e432b36d to your computer and use it in GitHub Desktop.
C# Smart Enum Pattern - Part 2: Optimizing by adding O(1) lookup and helpers
using System;
public class Program
{
public static void Main()
{
Console.WriteLine("--- C# Smart Enum Pattern: Part 2 (O(1) Optimization) ---\n");
int inputId = 2;
// 1. Check if it exists in the Dictionary
if (Status.Exists(inputId))
{
// 2. Retrieve the entire object (Instant lookup)
StatusValue? myStatus = Status.Get(inputId);
if (myStatus != null)
{
Console.WriteLine($"Found Object: {myStatus}");
Console.WriteLine($"Extracted ID: {myStatus.Id}");
Console.WriteLine($"Extracted Description: {myStatus.Description}");
}
}
// 3. Testing the default helper
Console.WriteLine($"\nTesting invalid ID (99): {Status.GetDescription(99)}");
}
}
using System.Collections.Generic;
using System.Linq;
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<int, StatusValue> _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";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment