Alan2
Alan2

Reputation: 24572

How can I determine if a variable is assigned a value that is present in an Enum?

I have this Enum:

namespace J.Enums
{
    public enum TH
    {
        Light = 0,
        Dark = 1
    }

    public static partial class Extensions
    {
        public static string Text(this TH theme)
        {
            switch (theme)
            {
                default:
                case TH.Light: return "Light";
                case TH.Dark: return "Dark";
            }
        }

        public static TH ToTheme(this string theme)
        {
            switch (theme)
            {
                default:
                case "Light": return TH.Light;
                case "Dark": return TH.Dark;
            }
        }
    }
}

If I have a variable a as follows:

var a = 88;

How can I determine if the value of a is a valid value for the Enum? Which in this case, it won't be.

Upvotes: 1

Views: 52

Answers (1)

Metheny
Metheny

Reputation: 1192

var isDefined = Enum.IsDefined(typeof(TH), a);

Upvotes: 6

Related Questions