Reputation: 14610
I have roughly 20+ enums that are all the same, but coming from different web service libraries, so when used they all need they're fully namespaced reference like this below
Where each enum is like this below
public enum yesnounspecified
{
unspecified,
yes,
no,
}
In my method I set all the values of a dynamic object, also from each of the different web services and I need to be able to set the enum to (yes/no) but not sure how to pass it in and use it
ex.
MyMethod("something", new WebServices_Production_TrustOnline_ARM.objectToFill());
public void MyMethod(string otherParam, dynamic someObject) {
// 'cigarettes' is a 'yesnospecified' enum
someObject.cigarettes = // need to set the enum value (yes/no) here but not sure how to pass it in and set it
}
Upvotes: 0
Views: 506
Reputation: 12007
Using reflection
public void MyMethod(string otherParam, object someObject)
{
var prop = someObject.GetType().GetProperty("cigarettes");
var enumType = prop.PropertyType;
prop.SetValue(someObject, Enum.Parse(enumType, "yes"), null);
}
This gets the information about the "cigarettes" property using reflection, including the enum type. Enum.Parse(enumType, string)
or Enum.ToObject(enumType, intValue)
can then be used to construct a value of this type. SetValue
writes the constructed value to the property.
Using generics
An alternative - if the value is fixed - would be to make the method generic and pass the enum value to the method:
public void MyMethod<T>(string otherParam, dynamic someObject, T value)
{
someObject.cigarettes = value;
}
Call: MyMethod("x", obj, yesnounspecified.yes);
Upvotes: 1