Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get enum Type by specifying its name in String

Suppose i have this Enum:

namespace BusinessRule
{
    public enum SalaryCriteria : int
        {
            [EnumDisplayName(DisplayName = "Per Month")]
            Per_Month = 1,
            [EnumDisplayName(DisplayName = "Per Year")]
            Per_Year = 2,
            [EnumDisplayName(DisplayName = "Per Week")]
            Per_Week = 3
        }
}

I have its name in a string variable like :

string EnumAtt = "SalaryCriteria";

i am trying to check if this Enum is defined by this name, and if defined i want to get its instance.i have tried like this, but type is returning null:

string EnumAtt = "SalaryCriteria";
Type myType1 = Type.GetType(EnumAtt);

i have also tried this:

string EnumAtt = "BusinessRule.SalaryCriteria";
Type myType1 = Type.GetType(EnumAtt);

any idea how i can achieve this.

like image 810
Ehsan Sajjad Avatar asked Aug 20 '14 12:08

Ehsan Sajjad


1 Answers

To search all loaded assemblies in the current AppDomain for a given enum -- without having the fully qualified assembly name -- you can do:

    public static Type GetEnumType(string enumName)
    {
        foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
        {
            var type = assembly.GetType(enumName);
            if (type == null)
                continue;
            if (type.IsEnum)
                return type;
        }
        return null;
    }

For instance (picking a semi-random enum which is not in my assembly):

var type1 = Type.GetType("System.Xml.Linq.LoadOptions") // Returns null.
var type2 = GetEnumType("System.Xml.Linq.LoadOptions") // Returns successfully.

You name should still include the namespace.

like image 142
dbc Avatar answered Oct 01 '22 18:10

dbc