Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# dynamic object - setting "Enum" value

Tags:

c#

dynamic

c#-4.0

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?
like image 615
Brazil Nut Avatar asked Dec 09 '22 20:12

Brazil Nut


1 Answers

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.

like image 54
Tim S. Avatar answered Dec 26 '22 07:12

Tim S.