views:

95

answers:

1

With Type.GetProperties() you can retrieve all properties of your current class and the public properties of the base-class. Is it somehow possible to get the private properties of the base-class too?

Thanks

class Base
{
    private string Foo { get; set; }
}

class Sub : Base
{
    private string Bar { get; set; }
}


        Sub s = new Sub();
        PropertyInfo[] pinfos = s.GetType().GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
        foreach (PropertyInfo p in pinfos)
        {
            Console.WriteLine(p.Name);
        }
        Console.ReadKey();

This will only print "Bar" because "Foo" is in the base-class and private.

+4  A: 

To get all properties (public + private/protected/internal, static + instance) of a given Type someType (maybe using GetType() to get someType):

PropertyInfo[] props = someType.BaseType.GetProperties(
        BindingFlags.NonPublic | BindingFlags.Public
        | BindingFlags.Instance | BindingFlags.Static)
Marc Gravell
In addition, it is possible to iterate through the base types (type = type.BaseType), until type.BaseType is null, to get a complete picture.
Eric Mickelsen
@Marc Gravell - sorry for the duplicate answer, didn't get the refresh before posting.
thedugas
unfortunately this does not work for private properties of the base class. only for inherited public and protected
Fabiano
@Fabiano - nonpublic includes private.
Marc Gravell
@Marc Gravell it seems that this only includes privates of the subclass but not of the baseclass. See additional information at the question
Fabiano
@Fabiano You need to call GetProperties() off of s.GetType().BaseType, not off of just GetType().
Andy
ok, so it seems you can't get all properties at once but have to check all basetypes by hand. But this will do it. Thanks
Fabiano