C# enum contains value

C#EnumsContains

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

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
}

Solution 3 - C#

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

Solution 4 - C#

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

Solution 5 - C#

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.

Solution 6 - C#

   public static T ConvertToEnum<T>(this string value)
    {
        if (typeof(T).BaseType != typeof(Enum))
        {
            throw new InvalidCastException("The specified object is not an enum.");
        }
        if (Enum.IsDefined(typeof(T), value.ToUpper()) == false)
        {
            throw new InvalidCastException("The parameter value doesn't exist in the specified enum.");
        }
        return (T)Enum.Parse(typeof(T), value.ToUpper());
    }

Solution 7 - C#

If your question is like "I have an enum type, enum MyEnum { OneEnumMember, OtherEnumMember }, and I'd like to have a function which tells whether this enum type contains a member with a specific name, then what you're looking for is the System.Enum.IsDefined method:

Enum.IsDefined(typeof(MyEnum), MyEnum.OneEnumMember); //returns true
Enum.IsDefined(typeof(MyEnum), "OtherEnumMember"); //returns true
Enum.IsDefined(typeof(MyEnum), "SomethingDifferent"); //returns false

If your question is like "I have an instance of an enum type, which has Flags attribute, and I'd like to have a function which tells whether this instance contains a specific enum value, then the function looks something like this:

public static bool ContainsValue<TEnum>(this TEnum e, TEnum val) where Enum: struct, IComparable, IFormattable, IConvertible
{
    if (!e.GetType().IsEnum)
        throw new ArgumentException("The type TEnum must be an enum type.", nameof(TEnum));

    dynamic val1 = e, val2 = val;
    return (val1 | val2) == val1;
}

Hope I could help.

Solution 8 - C#

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.

Solution 9 - C#

just cast the enum as:

string something = (string)myEnum;

and now comparison is easy as you like

Solution 10 - C#

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFred SmithView Question on Stackoverflow
Solution 1 - C#Sergey BerezovskiyView Answer on Stackoverflow
Solution 2 - C#LightStrikerView Answer on Stackoverflow
Solution 3 - C#Pranay RanaView Answer on Stackoverflow
Solution 4 - C#user1712937View Answer on Stackoverflow
Solution 5 - C#Akash MehtaView Answer on Stackoverflow
Solution 6 - C#c-sharpView Answer on Stackoverflow
Solution 7 - C#florienView Answer on Stackoverflow
Solution 8 - C#Cristian LupascuView Answer on Stackoverflow
Solution 9 - C#TalhaView Answer on Stackoverflow
Solution 10 - C#MaLKaV_eSView Answer on Stackoverflow