Jean Tehhe
Jean Tehhe

Reputation: 1337

Find value if value is part of Enum value

I have enum like the following and I wonder if I have a variable like string = March there is a simple way via API to find if the value (March )is part of the enum

public enum Month
{
    NotSet = 0,
    January = 1,
    February = 2,
    March = 3,
    April = 4,
    May = 5,
    June = 6,
    July = 7,
    August = 8,
    September = 9,
    October = 10,
    November = 11,
    December = 12
}

Upvotes: 1

Views: 84

Answers (3)

Soner Gönül
Soner Gönül

Reputation: 98740

How about using Enum.GetNames

Retrieves an array of the names of the constants in a specified enumeration.

Like;

bool b = Enum.GetNames(typeof(Month)).Contains("March");

Or as Raphaël mentioned;

if(Enum.GetName(typeof(Month), "March") != null)

Upvotes: 3

Marius Schulz
Marius Schulz

Reputation: 16440

If you just want to find out whether a certain value is defined in an enum, use Enum.IsDefined:

bool isDefined = Enum.IsDefined(typeof(Month), "March")

If you want to parse the value, have a look at Enum.TryParse:

Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object. The return value indicates whether the conversion succeeded.

You can use the following overload …

public static bool TryParse<TEnum>(
    string value,
    bool ignoreCase,
    out TEnum result
)

… like this:

Month month;
if (Enum.TryParse<Month>("March", true, out month)) {
    // ...
}

Upvotes: 4

Marc Gravell
Marc Gravell

Reputation: 1062520

You could do something like:

Month result;
if(System.Enum.TryParse(value, true, out result)) {
    // is defined
}

where the true there controls case-sensitivity (or not).

(note this is actually TryParse<Month>(...), but the compiler infers the <Month> from the out result, since result is defined as Month)

Upvotes: 5

Related Questions