Reputation: 2112
I have a string representation of an enum.
string val = "namespace_name.enum_name";
I can use this to get type of enum.
Type myType = Type.GetType(val);
Now I see myType.Name = actual_enum_name and other informations, good. I have tried to obtain the actual enum values using this information and not successful.
I have tried using Enum.Getvalues, however I got stuck in converting the myType, which is System.Type to EnumType, which is what Enum.Getvalues require(?).
I have tried to actually create an Enum object based on the information obtained and got stuck.
How can I get actual fields (list of members) of that enum from here?
Upvotes: 1
Views: 3104
Reputation: 3654
That should work as is, no conversion required. Enum.GetValues()
takes a Type
. The code below works.
namespace enumtest
{
public enum Mine
{
data1,
data2
}
class Program
{
static void Main(string[] args)
{
Type myenum = Type.GetType("enumtest.Mine");
foreach (var curr in Enum.GetValues(myenum))
{
Console.WriteLine(curr.ToString());
}
}
}
}
This allows you to construct instances of an enum value like this:
namespace enumtest
{
public enum Mine
{
data1,
data2
}
class Program
{
static void Main(string[] args)
{
Type myenum = Type.GetType("enumtest.Mine");
// Let's create an instance now
var values = Enum.GetValues(myenum);
var firstValue = values.GetValue(0);
Mine enumInstance = (Mine)Enum.Parse(myenum, firstValue.ToString());
Console.WriteLine("I have an instance of the enum! {0}", enumInstance);
}
}
}
Upvotes: 8
Reputation: 2116
Suppose i have an Enum ContactNumberType
then to get values use
string[] names = Enum.GetValues(typeof(ContactNumberType));
because GetValues()
method returns an array
Upvotes: 0