Skip to content

etartar/SmartEnums

Repository files navigation

Stop Using Primitive Enums in C# (Smart Enums Will Change Your Life)


  • Problem: Primitive enums force you to scatter behavior logic across switch statements throughout your codebase

  • Solution: Smart Enums are classes that combine enum-like functionality with rich, encapsulated behavior

  • Result: Type-safe, maintainable, testable domain objects that eliminate switch statement hell

  • Tech: C# with pattern matching, complete working examples for .NET


What Are Smart Enums?

Smart Enums are a pattern where you replace primitive enums with classes that act like enums but carry their own behavior.


Performance Considerations

Smart Enums are efficient:

✅ Static instances created once at startup (no allocations per-use)

✅ Equality comparison by integer ID (fast)

✅ Dictionary lookups for FromName/FromId (O(1))

✅ No boxing/unboxing like primitive enums


Best Practices Checklist

✅ Use private/protected constructors (prevent invalid instances)

✅ Inherit from a base SmartEnum class (DRY, consistent behavior)

✅ Store data in properties, not switch statements (eliminate redundancy)

✅ Make instances static readonly (single instance per value)

✅ Override Equals/GetHashCode (value equality by ID)

✅ Implement IEquatable (type-safe equality)

✅ Provide FromName/FromId methods (parsing from external sources)

✅ Use value converters for EF Core (database integration)

✅ Add JSON converters for serialization (API compatibility)

✅ Test behavior thoroughly (unit tests for all logic)

About

Smart Enums are a pattern where you replace primitive enums with classes that act like enums but carry their own behavior.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages