Programmaticallygetting type of an enum

  • Thread starter Thread starter Tom Hundley
  • Start date Start date
T

Tom Hundley

Scenario:
- I'm dumping an int value of myEnum into a table.
- I am getting that int value out of the table.
- I need to set myEnum equal to that int value

Easy enough:
private enum animals {cat=0, dog=1}
private animals myAnimal = (animals)1;

OK- so that works, and myAnimal is set to dog....

Problem:
I'm using reflection to go through a list of properties and am setting them
to their respective values from a table. My problem is that I need to
<<programmatically>> get type myAnimal.

private animals myAnimal = (System.Enum)1; //doesn't work
private animals myAnimal = 1; //doesn't work
private animals myAnimal = (programatically get type myAnimal)1; //this is
what I need

Anyone have any suggestions???

Thanks,
Tom
 
Tom,
Have you tried the Enum.ToObject function?

private animals myAnimal = Enum.ToObject(typeof(animals), 1);

Of course if you already have a variable of type System.Type you can use
that on ToObject instead of typeof. (if you are using reflection you should
have a variable of type System.Type!

Hope this helps
Jay
 
Yup, worked great. Thanks!

val = Enum.ToObject(pi.PropertyType,
(int)Source.GetType().GetProperty(_propertyPrefix +
pi.Name).GetValue(Source, null));
 
Back
Top