ardalis / SmartEnum

A base class for quickly and easily creating strongly typed enum replacements in C#.
MIT License
2.12k stars 164 forks source link

Introduce GetAll() method #293

Open RFBomb opened 1 year ago

RFBomb commented 1 year ago

I noticed that there is no 'GetAll()' method for this, as described on this page:

https://docs.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/enumeration-classes-over-enum-types

Could this be added to the base class?

/// <summary>
        /// Retrieve all enumerations of the SmartEnum
        /// </summary>
        /// <returns>new <see cref="IEnumerable{T}"/> of type <typeparamref name="T"/></returns>
        /// <seealso cref="https://docs.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/enumeration-classes-over-enum-types"/>
        public static IEnumerable<T> GetAll() =>
        typeof(T).GetFields(System.Reflection.BindingFlags.Public |
                            System.Reflection.BindingFlags.Static |
                            System.Reflection.BindingFlags.DeclaredOnly)
                 .Select(f => f.GetValue(null))
                 .Cast<T>();

This should get all of the static enum values defined

ardalis commented 1 year ago

Hmm, I don't think I'd implement it as shown, since it would pay the reflection cost every time. Typically when I need this I just add it myself and manually include all of the appropriate fields (in the order I'd like them to appear in).

ardalis commented 1 year ago

Possibly a source generator like this one could do the trick in a flexible and performant manner: https://stackoverflow.com/questions/66793030/replacing-reflection-with-source-generators

wilsonrivera commented 1 year ago

I don't know if this is something that still willing to implement into the library using source generators or if is being worked on, but if still interested and nobody has claimed it, I'd love to help with this!

ardalis commented 1 year ago

All yours @wilsonrivera !

RFBomb commented 1 year ago

Awesome!

RFBomb commented 1 year ago

Hey, I just realized that GetAllOptions() is a thing

https://github.com/ardalis/SmartEnum/blob/7117b76bc65dab300073acee7e32f5cf033b9e25/src/SmartEnum/SmartEnum.cs#L64

which I think is what I was looking for? But its currently a private item in the abstract class. Maybe it just needs to be exposed