I am trying to convert an Object to dynamic type but the conversion is failing with RunTimeBinder exception
Here is extension method to convert an object to Dynamic
public static dynamic ToDynamic(this object value)
{
IDictionary<string, object> expando = new ExpandoObject();
foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(value.GetType()))
expando.Add(property.Name, property.GetValue(value));
return expando as ExpandoObject;
}
you should use JsonConvert. Fist of all, Serialize object to string, then Deserialize string to dynamic.
string str = JsonConvert.SerializeObject(objectstring);
dynamic obj = JsonConvert.DeserializeObject(str);
The exception is:
Cannot dynamically invoke method 'Write' because it has a Conditional attribute
And when you check possible Debug.WriteLine inputs, "dynamic" is not one of them. So you need to cast it, to string for example:
string strForWriteLine = dynSum.ToString() as string;
Debug.WriteLine(strForWriteLine);
Hope this helps
*Edit: A little bit detail about dynSum.ToString() as string; When you just use ToString() you still get a dynamic string.
var strForWriteLine = dynSum.ToString();
strForWriteLine's type is dynamic { string }