InitLipton
InitLipton

Reputation: 2453

How to get attributes of bitwise enum

I've bitwise enum that has multiple values each with a description attribute.

    [Flags]
public enum ParkingAreaType
{
    [Description("Car Park")]
    CarPark = 1,

    [Description("Residential Permit")]
    ResidentialPermitZone = 2,

    [Description("Commercial Permit")]
    CommercialPermitZone = 4,

    [Description("On Street Parking")]
    OnStreetParking = 8,

    Any =
        CarPark | ResidentialPermitZone | CommercialPermitZone 
}

I've used and tried multiple extensions methods that i found on a few other questions quite similar to this

Getting attributes of Enum's value

How to get attributes of enum

Im currently using a the snippit of code from John Skeets EnumInternals https://github.com/jskeet/unconstrained-melody/blob/master/UnconstrainedMelody/EnumInternals.cs

private static string GetDescription(T value)
    {
        FieldInfo field = typeof(T).GetField(value.ToString());
        return field.GetCustomAttributes(typeof(DescriptionAttribute), false)
                    .Cast<DescriptionAttribute>()
                    .Select(x => x.Description)
                    .FirstOrDefault();
    }

The above code will work if i just pass in a single enum, but if i pass in a bitwise enum it will throw an Object Reference. I've tried a few different variations of the above from different examples but all with the same result.

I just cant figure out how to get a list of the descriptions that are passed in.

Upvotes: 2

Views: 87

Answers (1)

Vincent Ripoll
Vincent Ripoll

Reputation: 182

That's because there no field called CarPark | ResidentialPermitZone | CommercialPermitZone for instance (or CarPark | ResidentialPermitZone etc.)

You'll have to retrieve each value of the bit combinaison, for instance:

var result = new List<string>();
foreach (var parkingAreaType in Enum.GetValues(typeof(ParkingAreaType)))
{
    if (value.HasFlag(parkingAreaType))
    {
        result.Add(GetDescription(parkingAreaType));
    }
}

Upvotes: 3

Related Questions