4

I have a dynamic object (C# 4.0), In that i want to set an Enum value for a property dynamically, But i do not have an assembly reference for that type. Any idea on how to do this / is it possible to do this ?

dynamic vehicle = myObject;
vehicle.AddTires(); // working
vehicle.ConfigureEngine(); //working
vehicle.seat="Leather";//working
//Enum needs to be set for the Make
vehicle.Make = Manufacturer.Toyota; // how to do this?
3
  • 1
    eh, assembly reference for what type? Commented Oct 20, 2012 at 16:06
  • 2
    I believe he means, he doesnt have a reference to Manufacturer Commented Oct 20, 2012 at 16:07
  • Yes i do not have reference to "Manufacturer" Commented Oct 20, 2012 at 16:24

2 Answers 2

13

If c.Make always has a value (e.g. its type is Manufacturer, not Manufacturer? or the property doesn't exist at all before you set it):

c.Make = Enum.Parse(c.Make.GetType(), "Toyota");

If this won't work for you as-is, to use this approach, you'll need to somehow get a reference to the type Manufacturer. How complex this might be depends on how your dynamic type is set up. Another approach (e.g. if it's Manufacturer? and might be null) you might need to take is to use reflection to get the Make property to find what type it is.

Sign up to request clarification or add additional context in comments.

1 Comment

I just tried this, and it seems to be the only way I can get this to work.
2

Enum.Parse() has a return type of object, however, you can cast the returned object to dynamic to force it to look at the actual runtime type.

vehicle.Make = (dynamic)Enum.Parse(vehicle.Make.GetType(), "Toyota");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.