Jimenemex
Jimenemex

Reputation: 3166

Using dynamic to find a property

I have a set of messages which I cannot alter their structure, but all of them follow the same property structure after you drill into the first two. For example,

public class Animal {
    public Dog Doggy { get; set; }
}

public class MixedAnimal {
    public CatDog CatDoggy { get; set; }
}

public class Dog {
    public Name name { get; set; }
    public Age age { get; set; } 
}

public class CatDog {
    public Name name { get; set; }
    public Age age { get; set; } 
}

If I have a structure like this: SomeObj.Item where SomeObj is some object and Item is of type object which can hold either an Animal or MixedAnimal. How would I get to the value of either Dog or CatDog using the keyword dynamic?

I can get the top level object using SomeObj.Item as dynamic, and then do:

(SomeObj.Item as dynamic).Doggy.Name

but what I want is to just get the name without knowing the type of Item.

(SomeObj.Item as dynamic).(Something as dynamic).Name

Is this possible?

Upvotes: 1

Views: 59

Answers (1)

Tearth
Tearth

Reputation: 306

Using reflection is quite easy to resolve this problem. Something like this (general idea):

object animal = new Animal { Doggy = new Dog { age = 10, name = "Good boy" }};
var members = animal.GetType().GetMembers();

foreach (PropertyInfo member in members.Where(x => x is PropertyInfo))
{
    if (member.PropertyType.Name == "Dog" || member.PropertyType.Name == "CatDog")
    {
        var propertyValue = member.GetValue(animal);
        var propertyType = propertyValue.GetType();
        var nameMember = propertyType.GetProperty("name");
        var ageMember = propertyType.GetProperty("age");

        var nameValue = nameMember.GetValue(propertyValue);
        var ageValue = ageMember.GetValue(propertyValue);

        Console.WriteLine($"Name: {nameValue}, Age: {ageValue}");
    }
}

Everything you need to do additionally is providing list of type names which you want to process (like "Dog" or "CatDog" here).

Upvotes: 2

Related Questions