Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast dynamic object to type using reflection c#

Tags:

c#

reflection

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?

like image 478
Tim Geyssens Avatar asked Oct 05 '15 17:10

Tim Geyssens


1 Answers

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]);
like image 102
Eren Ersönmez Avatar answered Sep 20 '22 03:09

Eren Ersönmez