1

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.

Alan2
  • 23,493
  • 79
  • 256
  • 450
  • 1
    Use [Enum.TryParse()](https://learn.microsoft.com/en-us/dotnet/api/system.enum.tryparse?view=netframework-4.8)... – Idle_Mind Apr 25 '19 at 13:28
  • 4
    [Enum.IsDefined](https://learn.microsoft.com/en-us/dotnet/api/system.enum.isdefined?view=netframework-4.8) – 001 Apr 25 '19 at 13:29
  • Putting `default` above the other case labels seems odd. –  Apr 25 '19 at 13:32
  • Hi Amy, Would it be better to have a different line with default: return TH.Light; I'm not sure if there's any difference but welcome your advice. Thanks – Alan2 Apr 25 '19 at 13:42
  • Possible duplicate of [Is there a way to check if int is legal enum in C#?](https://stackoverflow.com/questions/2674730/is-there-a-way-to-check-if-int-is-legal-enum-in-c) – Sinatr Apr 25 '19 at 14:23

1 Answers1

6
var isDefined = Enum.IsDefined(typeof(TH), a);
Metheny
  • 1,112
  • 1
  • 11
  • 23
  • Thanks, this works and will accept. Unfortunately I now realise I have another problem but your answer was a big help. I'll write up another question for the next problem I have. – Alan2 Apr 25 '19 at 13:33