SmartEnum icon indicating copy to clipboard operation
SmartEnum copied to clipboard

Introduce GetAll() method

Open RFBomb opened this issue 2 years ago • 6 comments

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

RFBomb avatar Aug 02 '22 17:08 RFBomb

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 avatar Aug 02 '22 18:08 ardalis

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

ardalis avatar Aug 02 '22 18:08 ardalis

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!

wilsonrivera avatar Aug 05 '22 02:08 wilsonrivera

All yours @wilsonrivera !

ardalis avatar Aug 05 '22 15:08 ardalis

Awesome!

RFBomb avatar Aug 15 '22 20:08 RFBomb

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

RFBomb avatar Aug 19 '22 21:08 RFBomb