Cast dynamic object to type using reflection c#

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]);

dynamic is duck-typing a variable (i.e. delaying type check to run-time). It still holds a typed object but it's not checked during compile-time.

Thus, since an ExpandoObject is a type either if you assign it to a typed or dynamic reference, you can't cast or convert an ExpandoObject to a type just because it shares the same members as the target type.

BTW, since ExpandoObject implements IDictionary<string, object>, you can implement some kind of on-the-fly mapping from the ExpandoObject instance to target type where a member matches as an extension method:

public static class ExpandObjectExtensions
{
    public static TObject ToObject<TObject>(this IDictionary<string, object> someSource, BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public)
           where TObject : class, new ()
    {
        Contract.Requires(someSource != null);
        TObject targetObject = new TObject();
        Type targetObjectType = typeof (TObject);

        // Go through all bound target object type properties...
        foreach (PropertyInfo property in 
                    targetObjectType.GetProperties(bindingFlags))
        {
            // ...and check that both the target type property name and its type matches
            // its counterpart in the ExpandoObject
            if (someSource.ContainsKey(property.Name) 
                && property.PropertyType == someSource[property.Name].GetType())
            {
                property.SetValue(targetObject, someSource[property.Name]);
            }
        }

        return targetObject;
    }
}

Now, try the following code and it'll work as you expect:

public class A 
{
    public int Val1 { get; set; }
}

// Somewhere in your app...
dynamic expando = new ExpandoObject();
expando.Val1 = 11;

// Now you got a new instance of A where its Val1 has been set to 11!
A instanceOfA = ((ExpandoObject)expando).ToObject<A>();

Actually, I've based this answer on other Q&A where I could address a similar issue of mapping objects to dictionary and viceversa: Mapping object to dictionary and vice versa.

Tags:

C#

Reflection