#1,026 – Checking a Flagged enum Type for Validity

You normally use the Enum.IsDefined method to check whether a particular enum value is a valid value.  This method does not work on flagged enums.

Assuming the following enum type:

    [Flags]
    public enum Talents
    {
        Singing = 1,
        Dancing = 2,
        Juggling = 4,
        JokeTelling = 8
    };

Enum.IsDefined will not work for all values of the flagged enum:

            Talents myTalent = Talents.JokeTelling | Talents.Juggling;
            // Returns false
            bool isDefCheck = Enum.IsDefined(typeof(Talents), myTalent);

To properly check for validity, you can convert the enum to a string and then try parsing as an integer. If the value is invalid, ToString() will convert to a simple integer and the parse will then succeed.

        private static void CheckTalents(Talents t)
        {
            int intTest;
            if (int.TryParse(t.ToString(), out intTest))
                Console.WriteLine("Talents not ok");
            else
                Console.WriteLine("Talents ok");
        }

1026-001

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a comment