chuckd
chuckd

Reputation: 14610

How to pass a generic enum to a method and set it to a dynamic object inside the method

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

  1. WebServices_Production_TrustOnline_ARM.yesnounspecified
  2. WebServices_Development_TrustOnline_ARM.yesnounspecified
  3. WebServices_Production_TrustOnline_BW.yesnounspecified
  4. WebServices_Development_TrustOnline_BW.yesnounspecified
  5. etc
  6. etc up to 20+

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

Answers (1)

Klaus Gütter
Klaus Gütter

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

Related Questions