Reputation: 39354
I have the enum:
public enum Colors { Yellow, Red }
Then I have a string:
String enumName = "Colors";
Is it possible to get an enum instance from the enumName? Something like:
Enum colors = // get enum with name "Colors".
Thank You, Miguel
Upvotes: 0
Views: 176
Reputation: 10257
are you looking for something like this?
using System;
using System.Linq;
namespace Stuff
{
class Program
{
static void Main(string[] args)
{
string enumName = "Colors";
string value = "Red";
var loadedPublicTypes = AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => x.GetExportedTypes());
var possibleEnums = loadedPublicTypes.Where(x => x.IsEnum && x.Name == enumName);
foreach (var e in possibleEnums)
{
Console.WriteLine("{0} is{1} a member of {2}", value, Enum.GetNames(e).Contains(value) ? "" : " not", e.FullName);
}
}
}
public enum Colors
{
Red,
Yellow
}
}
Upvotes: 1
Reputation: 124686
You need the full name of the enumeration type (e.g. System.Drawing.KnownColor, System.Drawing
, or Microsoft.MediaCenter.UI.Colors, Microsoft.MediaCenter.UI
).
Once you have this, you can use reflection to create an instance of the corresponding enum.
Upvotes: 0
Reputation: 5495
You could use a dynamic type and find a variable by name, but you would have to have an instance of all the enums you want to include in your search.
Check out the following post: Getting variable by name in C#.
Upvotes: 0