Search code examples
c#dynamicxamarin.androidexpandoobject

Dynamic object throwing 'does not contain definition for...' exception when member exists in collection


I am having an issue with this piece of code:

IList<dynamic> list = await GetApiUrl("EndpointName").GetJsonListAsync(); // Call to API using FLUrl

List<Model> modelList = new List<Model>();
foreach(var item in list) 
{
    var model = new Model() 
    {
        GuidId = new Guid(item.Id),
        Name = item.Name
    }

    modelList.Add(model);
}

public class Model 
{
    public Guid GuidId { get; set; }
    public string Name { get; set; }
}

Sample API response:

[
    {
        "Id": "9232f70b-bdc6-402c-9fab-250977e9a0c1",
        "Name": "Sample name"
    },
    {
        "Id": "0f746670-e057-4c13-9a82-c98419d09e55",
        "Name": "Sample name"
    },
    {
        "Id": "370cce64-37f6-4e71-a44e-32168c3ef2cb",
        "Name": "Sample name"
    }
]

I get this exception when accessing item.Id or item.Name even though I have confirmed that item object does have Id and Name members (see attached image below).

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 
''System.Dynamic.ExpandoObject' does not contain a definition for 'Id''

enter image description here

What am I doing wrong here?


Solution

  • I've found what was causing the issue but it is rather wierd.

    The code is part of Xamarin.Android application and since I started working on the project, exception settings in IDE were wierd to me because all exceptions had 'Break when this exception happens' disabled. Yesterday (cuz I was sick of digging through files to find where the exception was thrown) I have enabled that checkbox in order to see see where exception was thrown in runtime along with exception details.

    I had an enlightenment when I started the app without debugging and it actually worked (eventhough exception was still being thrown). Then I remembered what I did yesterday and reverted exception settings in IDE and, TA DAAA, it worked.

    I guess this has something to do with Xamarin and the way it handles exceptions. If someone can elaborate on this behavior I will be happy to accept his/her answer