Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I am trying to convert an Object to dynamic type but the conversion is failing with RunTimeBinder exception

I am trying to convert an Object to dynamic type but the conversion is failing with RunTimeBinder exception. I tried using two methods that I came across in Stackoverflow answers.

Code 1:

object objSum;
dynamic dynSum;
objSum = dataTableColumnChart.Compute(String.Format("Count({0})", strColumnName), "");
dynSum = Convert.ChangeType(objSum, objSum.GetType());\
Debug.Writeline(dynSum);

Code 2:

dynSum=objSum;
Debug.Writeline(dynSum);

The exception thrown is this:

A first chance exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in Unknown Module.

Please note that in both cases exception is thrown when Debug statement is executed.

like image 770
JKay Avatar asked Mar 22 '16 06:03

JKay


1 Answers

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;
    }
like image 155
Anand Patel Avatar answered Sep 21 '22 00:09

Anand Patel