C# enum contains value

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

something like that:

private bool EnumContainValue(Enum myEnum, string myValue)
{
     return Enum.GetValues(typeof(myEnum))
                .ToString().ToUpper().Contains(myValue.ToUpper()); 
}

But it doesn't work because myEnum parameter is not recognized.


Why not use

Enum.IsDefined(typeof(myEnum), value);

BTW it's nice to create generic Enum<T> class, which wraps around calls to Enum (actually I wonder why something like this was not added to Framework 2.0 or later):

public static class Enum<T>
{
    public static bool IsDefined(string name)
    {
        return Enum.IsDefined(typeof(T), name);
    }

    public static bool IsDefined(T value)
    {
        return Enum.IsDefined(typeof(T), value);
    }

    public static IEnumerable<T> GetValues()
    {
        return Enum.GetValues(typeof(T)).Cast<T>();
    }
    // etc
}

This allows to avoid all this typeof stuff and use strongly-typed values:

Enum<StringSplitOptions>.IsDefined("None")

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 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));

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...


Also can use this:

    enum myEnum2 { ab, st, top, under, below }
    static void Main(string[] args)
    {
        myEnum2 r;
        string name = "ab";
        bool result = Enum.TryParse(name, out r);
    }

The result will contain whether the value is contained in enum or not.