I have an enum
enum myEnum2 { ab, st, top, under, below}
I would like to write a function to test if a given value is included in myEnum
I think that you go wrong when using ToString().
Try making a Linq query
private bool EnumContainValue(Enum myEnum, string myValue)
{
var query = from enumVal in Enum.GetNames(typeof(GM)).ToList()
where enumVal == myValue
select enumVal;
return query.Count() == 1;
}
What you're doing with ToString() in this case is to:
Enum.GetValues(typeof(myEnum)).ToString()...
instead you should write:
Enum.GetValues(typeof(myEnum).ToString()...
The difference is in the parentheses...
No need to write your own:
// Summary:
// Returns an indication whether a constant with a specified value exists in
// a specified enumeration.
//
// Parameters:
// enumType:
// An enumeration type.
//
// value:
// The value or name of a constant in enumType.
//
// Returns:
// true if a constant in enumType has a value equal to value; otherwise, false.
public static bool IsDefined(Type enumType, object value);
Example:
if (System.Enum.IsDefined(MyEnumType, MyValue))
{
// Do something
}
just cast the enum as:
string something = (string)myEnum;
and now comparison is easy as you like
Use the correct name of the enum (myEnum2
).
Also, if you're testing against a string value you may want to use GetNames
instead of GetValues
.
just use this method
Enum.IsDefined Method - Returns an indication whether a constant with a specified value exists in a specified enumeration
Example
enum myEnum2 { ab, st, top, under, below};
myEnum2 value = myEnum2.ab;
Console.WriteLine("{0:D} Exists: {1}",
value, myEnum2.IsDefined(typeof(myEnum2), value));