I would like to implement a method with the following signature
dynamic Cast(object obj, Type castTo);
Anyone know how to do that? obj defi
Slight modification on @JRodd version to support objects coming from Json (JObject)
public static dynamic ToDynamic(this object value)
{
IDictionary expando = new ExpandoObject();
//Get the type of object
Type t = value.GetType();
//If is Dynamic Expando object
if (t.Equals(typeof(ExpandoObject)))
{
foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(value.GetType()))
expando.Add(property.Name, property.GetValue(value));
}
//If coming from Json object
else if (t.Equals(typeof(JObject)))
{
foreach (JProperty property in (JToken)value)
expando.Add(property.Name, property.Value);
}
else //Try converting a regular object
{
string str = JsonConvert.SerializeObject(value);
ExpandoObject obj = JsonConvert.DeserializeObject(str);
return obj;
}
return expando as ExpandoObject;
}