Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the properties of an inherited object when the parameter is declared as a base type?

I have a simple program that uses reflection to print out the properties and values of the supplied class.

class BaseClass
{
    public string A
    {
        get { return "BaseClass"; }
    }
}

class Child1 : BaseClass
{
    public string Child1Name {
        get { return "Child1"; }
    }
}

class Child2 : BaseClass
{
    public string Child2Name
    {
        get { return "Child2"; }
    }
}

class Program
{
    static void Main(string[] args)
    {
        var child1 = new Child1();
        var child2 = new Child2();
        SomeMethod(child1);
        SomeMethod(child2);

        Console.ReadKey();
    }

    static void SomeMethod(BaseClass baseClass)
    {
        PrintProperties(baseClass);
    }

    static void PrintProperties<T>(T entity)
    {
        var type = typeof(T);

        foreach (var targetPropInfo in type.GetProperties())
        {
            var value = type.GetProperty(targetPropInfo.Name).GetValue(entity);
            Console.WriteLine("{0}: {1}", targetPropInfo.Name, value);
        }
        Console.WriteLine("");
    }
}

The problem is that it only prints out the BaseClass properties because I am using generics and passing in the BaseClass into the PrintProperties method.

Output:

A: BaseClass

A: BaseClass

How do I access the properties of the Child classes? I would like an output like:

A: BaseClass
Child1Name: Child1

A: BaseClass
Child2Name: Child2

like image 709
Chris Avatar asked Dec 24 '22 20:12

Chris


1 Answers

The problem here is that you're using typeof(T) in PrintProperties, but the T in your example is BaseClass because that's the type of the parameter you give it from SomeMethod.

In your example, remove SomeMethod, call the PrintProperties method directly and it'll work.

A simpler way would be to use entity.GetType() instead of typeof(T). That way, no matter what the generic type is, you'll always get the true type of the object.

like image 137
Solal Pirelli Avatar answered Dec 27 '22 10:12

Solal Pirelli