germanSharper
germanSharper

Reputation: 971

How can I get a value from an unknown enum in C#?

I'm actually programming a deepToString-Method that extends object. This uses reflection to get each property of an object and calls the deepToString-Method for this property. Everything works fine except of Enums. If I try to use PropertyInfo.GetValue() with an enum, it allways returns zero.

How can I get the real int-Value? What am I missing?

Upvotes: 3

Views: 3254

Answers (2)

the_joric
the_joric

Reputation: 12226

public enum Foo
{
    Boo,
    Koo
}

public Foo foo { get; set; }

[Fact]
public void FactMethodName()
{
    foo = Foo.Koo;
    var propertyInfo = this.GetType().GetProperty("foo");
    if (propertyInfo.PropertyType.IsEnum)
    {
        var value = propertyInfo.GetValue(this, null);
        Console.Out.WriteLine("value = {0}", value); //prints Koo
        int asInt = (int)value;
        Console.Out.WriteLine("asInt = {0}", asInt); //prints 1
    }
}

Upvotes: 1

vulkanino
vulkanino

Reputation: 9134

foreach (PropertyInfo propertyInfo in your_class.GetType().GetProperties())
{
  if ((info.PropertyType.IsEnum) && (info.PropertyType.IsPublic))
  {
    foreach (FieldInfo fInfo in this.propertyInfo.PropertyType.GetFields(BindingFlags.Public | BindingFlags.Static))
    {
      ListItem item = new ListItem(fInfo.Name, fInfo.GetRawConstantValue().ToString());
      //... use it
    }
  }
}

I have to add that reflection is EVIL. Rare are the occasions where it is really needed..

Upvotes: 2

Related Questions