SmartEnum icon indicating copy to clipboard operation
SmartEnum copied to clipboard

Allow to include private/internal members in GetAllOptions()

Open cmenzi opened this issue 4 years ago • 2 comments
trafficstars

I have currently the following requirement to an Enum should be only be created via a static method including some configuration to preserve the immutability.

As you can see, I like to define the EmptyEnrichment. This works perfectly fine until, I would like to do a TryFromValue.

Here the EmptyEnrichment not get listed to verify that's possible / valid enum.

When I make it public, it works. But I don't like to offer this to the clients.

Maybe an option to include private or internal members would address my issue. Or do you have better idea/design?

Example

public sealed class TransformationType : SmartEnum<TransformationType, string>
{
        private static readonly TransformationType EmptyEnrichment = new TransformationType(nameof(Enrichment), "enrichment");

        private TransformationType(string name, string value)
            : this(name, value, null)
        {
        }

        private TransformationType(string name, string value, object data)
            : base(name, value)
        {
            Data = data;
        }

        public static TransformationType Enrichment(
            Action<ITransformationInputConfigurator> inputConfigurator,
            Action<IEnrichmentMappingConfigurator> mappingConfigurator,
            Action<ITransformationOutputConfigurator> outputConfigurator)
        {
            var enrichmentConfigurator = new EnrichmentConfigurator();

            inputConfigurator(enrichmentConfigurator);
            mappingConfigurator(enrichmentConfigurator);
            outputConfigurator(enrichmentConfigurator);

            return new TransformationType(EmptyEnrichment.Name, EmptyEnrichment.Value, enrichmentConfigurator.Data);
        }
}

cmenzi avatar Feb 19 '21 08:02 cmenzi

Can you show the code that isn't working? The TryFromValue? I'm not seeing the problem, yet.

ardalis avatar Feb 19 '21 13:02 ardalis

Sure!

The issue is here: https://github.com/ardalis/SmartEnum/blob/master/src/SmartEnum/TypeExtensions.cs#L12 where the binding flags only include BindingFlags.Public members.

This means that a defined private member in enumeration class is not added to the options list of TEnum in the method GetAllOptions.

This results in, that an the defined private member EmptyEnrichment with the value enrichment from above is not found and TryFromValue returns false.

Example

if(TransformationType.TryFromValue("enrichment", out var transformationType)
{
}

cmenzi avatar Feb 19 '21 16:02 cmenzi