Consider the following code
var currentType = Type.GetType("Some.Type, Some");
dynamic myDynamic = new System.Dynamic.ExpandoObject();
myDynamic.A = "A";
var objectInCorrectType = ???
How do I cast the dynamic to the currentType?
You can't cast a dynamic object to a specific type, as @Lasse commented.
However, your question mentions "reflection", so I suspect you're looking for a way to simply map property values (i.e. "creating a new X and copying over values, etc." in Lasse's comment):
...
myDynamic.A = "A";
// get settable public properties of the type
var props = currentType.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(x => x.GetSetMethod() != null);
// create an instance of the type
var obj = Activator.CreateInstance(currentType);
// set property values using reflection
var values = (IDictionary<string,object>)myDynamic;
foreach(var prop in props)
prop.SetValue(obj, values[prop.Name]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With