How To Create Smart Enums in C# With Rich Behavior

52,564
122
Publicado 2022-11-08
Get the source code for this video for FREE → the-dotnet-weekly.ck.page/smart-enums
☄️ Master the Modular Monolith Architecture: bit.ly/3SXlzSt
📌 Accelerate your Clean Architecture skills: bit.ly/3PupkOJ
🚀 Support me on Patreon to access the source code: www.patreon.com/milanjovanovic

Enums are a great way to improve readability in your code. But enums in C# have a minor problem - you can't add behavior to enum elements. You can only work with enum values. In this, I will show you how you can create a custom smart enum implementation that can contain behavior.

Join my weekly .NET newsletter:
www.milanjovanovic.tech/

Read my Blog here:
www.milanjovanovic.tech/blog

Subscribe for more:
youtube.com/c/MilanJovanovicTech?sub_confirmation=…

Chapters
0:00 The problem with C# enums
1:16 Creating the Enumeration class
5:11 Implementing Enumeration in CreditCard
8:44 Completing Enumeration implementation
13:17 Adding logic to CreditCard en

Todos los comentarios (21)
  • @mrogalski
    Okay, I get it that all companies are trying to obfuscate the code even though it is compiled but this ... this seems like a perfect example of overengineering. There's basically zero profit from your solution and it only adds huge overhead on the "enumeration". This discount example could be simplified with proper enum and extension methods or simple attributes. Both mentioned methods gives no overhead, no additional abstraction layers, no additional class files.. I really tried to find any reason for this but I can't. It's impossible to justify this approach
  • Seems like solution which solve a problem thas doesn't need to be solved. If you need more than just an enum, use classes or structures.
  • @janedoe6182
    10:12 CreateEnumerations() method is overhead. You can push each enum member to the dictionary in Enumeration<T> constructor
  • Thanks for sharing this idea. This is a nice approach. I would still say this is a bit overkill. When you need to implement new credit card you have to go back to the CreditCard class and modify it. I believe this can be modified a bit to make it more solid friendly.
  • @pureevil379
    Essentially creating a way to work with classes that would inherit from a similar parent in an enum style way. I like it for adding some structure to the code base in working with inherited classes. Thanks
  • @tomtran6936
    Woa. It's quite a good example around many practices and aspects of OOP.
  • @mrsajjad30
    Subscribed. I liked the way you explain things in a easy manner.
  • Hi Milan, firstly, allow me thank you for your high quality content. I think what you are trying to do here is to discover SUM types that C# has refused to add to the language. There is a library though LanguageExt that supports them, it generates most of the code for you too. Thank you
  • @svorskemattias
    Looks like strategy pattern + a storable identifier to me. Can you enforce exhaustive pattermatching switch expressions with this?
  • @ApacheGamingUK
    I've used a setup very similar to this to implement string-based enums, as a way to combat primitive obsessions, or "magic strings". It's also good to add implicit converters to and from strings. I'd imagine that using this with complex classes, instead of primitives, could lead to issues with polymorphism, and hierarchy, if you don't create team-wide rules as to their usage. I wonder how much of the bloat within this could be extracted via source generators, using attributes on the public static fields(/properties?) to set discount values. Personally, I don't think that an "Enum" should be used to discriminate complex information, or business logic, so a source generator that allows basic distinct information to be assigned doesn't stretch it too far. Otherwise, a dictionary wrapper, or repo would be more suitable. The thought of piling business logic into ever-more-bloated private nested classes just leaves a nasty taste in my mouth.
  • @antonmartyniuk
    It's a very interesting concept by the way. Wish C# could have something similar out of the box like some sort of smart enums exist in Java
  • @billacount
    there are a lot of issues with this code. I tried following through and writing the code using my VS 2019 environment and it didn't work on many different things first when I tried to follow your convention of removing the name space curly braces namespace SmartEnum{} and replace it with SmartEnum; that failed. when I tried using protected init; I was unable to When I tried to use TENum? it also threw an exception I think these are all configuration issues. but you should address them before starting the video so that we can follow along and use your code thanks for the idea but can you provide some help in rectifying these issues?
  • @mylesdavies9476
    Getting a lot of stick for this video in the comments which is uncalled for. I found it interesting, thanks
  • In my mind, the real benefit of rich enums (in other languages) is that they’re value semantic. That is, a performant way to represent complex data structures. As soon as you use classes you’re using the heap, and to boot you’re using reflection. Kind of defeats the point IMO.
  • @benlewies8828
    I think I may be missing something, but the static Enumerator variable will be overwritten in memory each time you call a different child class of Enumerator?
  • @benlewies8828
    I can see this being extended to be used in conjunction with caching and persistence, and for use with the strategy pattern.