Question

Is there a way to print all the enums in C# class library or namespace? I want the name to be printed with its values.

For example if I have the namespace as below:

namespace MyCompany.SystemLib
{
    public enum ItemStatus
    {
        None = 0,
        Active = 1,
        Inactive = 2    
    }

    public enum MyEnum
    {
        EnumVal1 = 1,
        EnumVal2 = 2,
        EnumVal3 = 3,

    }   
}

I would like to print them delimited as below (to a textfile) Bullet given for clarity here not needed in output.

  • ItemStatus,None=0,Active=1,Inactive=1
  • MyEnum,EnumVal1=1,EnumVal2=2,EnumVal3

I don't know where to start. Any help is appreciated.

Was it helpful?

Solution

Reflection to the rescue!

List<string> allEnums = new List<string>();
var allTypes = AppDomain.CurrentDomain.GetAssemblies().SelectMany(assembly => assembly.GetTypes());

foreach (Type type in allTypes)
{
    if (type.Namespace == "MyCompany.SystemLib" && type.IsEnum)
    {
        string enumLine = type.Name + ",";
        foreach (var enumValue in Enum.GetValues(type))
        {
            enumLine += enumValue + "=" + ((int)enumValue).ToString() + ",";
        }

        allEnums.Add(enumLine);
    }
}

The first line goes over all assemblies currently loaded in memory (because a namespace can be scattered over many DLLs and EXEs) and filters out those in the right namespace, and that are enums. This can be streamlined into a LINQ query if you'd like.

The inner loop goes over the values of the enum, and uses GetName to match the string to the value.

OTHER TIPS

Try using the Enum.GetNames() method.

It can be done using LINQ and Reflection ofcourse.

var asm = Assembly.LoadFrom("path of the assembly");
var enums = asm.GetTypes().Where(x => x.IsEnum).ToList();

var result = enums
            .Select(
                x =>
                    string.Format("{0},{1}", x.Name,
                        string.Join(",",Enum.GetNames(x)
                        .Select(e => string.Format("{0}={1}", e, (int)Enum.Parse(x, e))))));

File.WriteAllLines("path", result);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top