mardi 21 novembre 2023

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: ''object' does not contain a definition for 'Name''

Trying to solve this mistery! I have this dynamics structure that works only in some cases: This is where I mount the dynamic object

    string President { get; set; } = "Boss";
    string Name { get; set; } = "USA";
    int Population { get; set; } = 600000;
    Region[] Regions { get; set; }
    
    internal dynamic CreateRegion(dynamic req)
    {
        Regions = new Region[] { new("NY"), new("MI") };
            return new
  {
      Name,
      Population,
      Regions,
      President
  };
  
    
    }

this is where I consume my dynamic type:

var response = italy.CreateRegion(req);
Console.WriteLine(response);
Console.WriteLine(response.Name);
Console.WriteLine(response.Population);
Console.WriteLine(response.President);
foreach (var region in response.Regions)
{
    Console.WriteLine(region.Name.ToString());
}

The field Name is present in the object and I can see this. But When I try to call it, it returns the error:

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: ''object' does not contain a definition for 'Name''

enter image description here enter image description here the tricky thing is that if I remove

Regions = Regions

, the from

return new
{
    Name = this.Name,
    Population = this.Population,
    Regions = Regions,
    Presindent = this.President,
};




Aucun commentaire:

Enregistrer un commentaire