Why does GetType() give me the derived type but GetType().GetProperties() gives me the base class properties?

106 views Asked by At

I'm trying to avoid code duplication by having a function in a base class that creates a list of properties which implement a specific interface.

When I call the function it doesn't work as I hope.

While trying to debug, I found the following results which I don't understand:

Call GetType() gives me the derived type. (Which is what I want.)

However, GetType().GetProperties() only gives me the base class properties and not the properties in the type returned by GetType().

interface IParameter
{
    string ParameterValue { get; }
}

class SearchBase
{
    public string SearchName { get; set; }

    protected List<IParameter> ListOfParameters()
    {
        // this gives me the derived type object of SearchOne
        var type = GetType();

        // this only gives me the base class properties of SearchBase
        var typeProperteis = type.GetProperties();

        // I want this to return a list of all the IParameter properties in the derived classes 
        return GetType().GetProperties().Where(p => typeof(IParameter).IsAssignableFrom(p.PropertyType)).Select(x => (IParameter)x.GetValue(this)).ToList();
    }
}

class SearchOne : SearchBase
{
    public IParameter Parameter1 { get; set; }
    public IParameter Parameter2 { get; set; }
    public IParameter Parameter3 { get; set; }

    public void DoSomething()
    {
        var properties = ListOfParameters();
    }
}

It seems counter intuitive to me that it will give me the derived type from the base type but not the properties of the derived type. (I could understand if it only gave me the base class in both examples, but I'm confused why it's a bit of each.)

Edit:

It turns out the property in my derived type wasn't marked public. Once I made it public it was returned in the list.

1

There are 1 answers

2
Mustafa Özçetin On BEST ANSWER

The answer is in the docs: Type.GetProperties() Method says:

It returns all public instance and static properties, both those defined by the type represented by the current Type object as well as those inherited from its base types.