Zachwiany
Zachwiany

Reputation: 43

Set property of enum type given by string

I got some enum's in my class, it's look like this one:

public enum A { A1, A2 }
public enum B { B1, B2 }

Problem is when i try to read items from XML file (each field given by property name and property value - both string).

Now i got my method which is setting value of single property (there is only part with isEnum check).

public A classfield
{
  get;
  set;
}
public bool DynamicallySetItemProperty(string name, string value)
{
  // value = "A1" or "A2"; - value given in string.
  // name = "classfield"; - name of property.
  PropertyInfo p = this.GetType().GetProperty(name);
  if (p.PropertyType.IsEnum)
  {
    var a = (A) Enum.Parse(typeof(A), value);
    p.SetValue(this, a);
  }
  return true;
}

But in this one i'm not checking if field is A or B-enum.

Is there any way to make my method checking type of enum and then parsing my string to this enum, something like this one:

public bool DynamicallySetItemProperty(string name,string value)
{
  PropertyInfo p = this.GetType().GetProperty(name);
  if (p.PropertyType.IsEnum)
  {    
    var a = (p.GetType()) Enum.Parse(typeof(p.GetType()), value); // <- it doesn't work
    p.SetValue(this, a);
  }
  return true;
}

So i need to check property for its enum-type and then parse my string value to this enum-type without using if/else or switch statement (it's problematic when i got a lot of enum types). Is there any easy way to do it?

Upvotes: 4

Views: 6708

Answers (2)

Ren&#233; Vogt
Ren&#233; Vogt

Reputation: 43876

There is no need to further check the type. Enum.Parse() takes the type as first parameter, and the type you need is p.PropertyType (as this is the type of the property. SetValue() takes an object as parameter for the value anyway, so there is no need to cast the return value of Enum.Parse():

PropertyInfo p = this.GetType().GetProperty(name);
if (p.PropertyType.IsEnum)
   p.SetValue(this, Enum.Parse(p.PropertyType, value));

Note that p.GetType() returns the Type instance for PropertyInfo, not the enum type!

Upvotes: 7

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37000

You won´t need this, because PropertyInfo.SetValue expects an instance of object as second parameter. So you won´t need to take care on the specific type and simply can use this:

var parsedValue = Enum.Parse(p.PropertyType, value);
p.SetValue(this, parsedValue, null);

Upvotes: 0

Related Questions