We have a common component in our source which contains all the enums (approx 300!) for a very large application.
Is there any way, using either C# or VB.NET, to iterate through all of them in order to perform an action on each one?
The question How to iterate all “public string” properties in a .net class is almost relevant but the enums I am dealing with are a mix of types
Something along these lines?
var query = Assembly.GetExecutingAssembly()
.GetTypes()
.Where(t => t.IsEnum && t.IsPublic);
foreach (Type t in query)
{
Console.WriteLine(t);
}
This should get you started. Iterate through the types in the loaded assemblies; and check whether they are an enum:
List<string> enumValues = new List<string>();
foreach(Type t in AppDomain.CurrentDomain.GetAssemblies().Select(a=>a.GetTypes().Where(t=>t.IsEnum)))
{
enumValues.AddRange(Enum.GetNames(t));
}
Once all of your assemblies are loaded, you can iterate through each Assembly and call GetTypes() to return all types (you can optionally get private types as well, though this will take longer). You can filter the types by IsEnum to get only those that are enum types. Note that this will also return all BCL Enum types. If you don't want the BCL types, you'll need to filter them out. You can get rid of most of them by ignoring assemblies whose names start with "System". Alternately, you can check that the path contains your local path, assuming all of your project assemblies are local to your EXE.
Assuming you have the assembly on which the enums resides.
IEnumerable<Type> enums = assembly.GetTypes.Where(t => t.IsEmum);
If you have all the enums
compiled into a common enum
you could use something along the lines of this:
using System;
namespace SomeApp
{
class Program
{
static void Main(string[] args)
{
foreach(MyEnum target in Enum.GetValues(typeof(MyEnum)))
{
Console.WriteLine(target.ToString());
// You can obviously perform an action on each one here.
}
}
}
enum MyEnum
{
One,
Two,
Three,
Four,
Five
};
}
/*
Prints...
One
Two
Three
Four
Five
*/
Hopefully this can get you started down the right path.