"'System.Dynamic.ExpandoObject' does not contain a definition for "PropertyName"

Learner picture Learner · Aug 16, 2013 · Viewed 12.1k times · Source

I have the following code that generates Dynamic object from XML file:

C#

    private static List<dynamic> GetClientObject()
    {
        var xDoc = XDocument.Load(new StreamReader(xmlPath + @"\client.xml"));
        dynamic root = new ExpandoObject();
        XmlToDynamic.Parse(root, xDoc.Elements().First());
        List<dynamic> clients = new List<dynamic>();

        for (int i = 0; i < root.clients.client.Count; i++)
        {
            clients.Add(new ExpandoObject());
            clients[i].Id = root.clients.client[i].id;
            clients[i].Name = root.clients.client[i].name;
            List<string> list = new List<string>();

            for (int j = 0; j < root.clients.client[i].emails.email.Count; j++)
            {
                list.Add(root.clients.client[i].emails.email[j].ToString());
            }

            clients[i].Email = string.Join(",", list);
        }
        return clients;
    }

XML

<clients>
    <client>
        <id>SomeId</id>
        <name>SomeName</name>
        <emails>
            <email>[email protected]</email>
            <email>[email protected]</email>
            <email>[email protected]</email>
        </emails>
        <timezone>Mountain Standard Time</timezone>
    </client>
</clients>

The code works fine but I always see the following Exception(multiple times) in the IntelliTrace:

Exception:Thrown: "'System.Dynamic.ExpandoObject' does not contain a definition for 'client'" (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException) A Microsoft.CSharp.RuntimeBinder.RuntimeBinderException was thrown: "'System.Dynamic.ExpandoObject' does not contain a definition for 'client'"

Is there anything wrong with my code?

Answer

Colin Thomsen picture Colin Thomsen · Aug 21, 2013

I gather this is expected behavior when using an ExpandoObject. I took a look at the IntelliTrace log for this code and the entries for the exceptions you are seeing are paired up:

  • Exception:Thrown: "'System.Dynamic.ExpandoObject' does not contain a definition for 'clients'" (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException)
  • Exception:Caught: "'System.Dynamic.ExpandoObject' does not contain a definition for 'clients'" (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException)

i.e. The exception is being thrown and then caught. If you look at the Call Stack Window you will see that the throws and catches are within the .NET Framework.

BTW, I did have to make a small change to your code to make it run: I changed: root.clients.client.Count to root.clients.Count in the for loop.