Search code examples
c#.netsystem.reflection

Get only protected members via .net reflection


This returns all non-public instance properties:

var instanceNonPublic = currentType.GetProperties (BindingFlags.Instance |
                                                   BindingFlags.NonPublic);

But is there any way to determine which access modifier applies to each property? private, internal or protected?


Solution

  • Since properties are made of get method and set method you can iterate them and filter the relevant PropertyInfos using their get and set methods' access modifiers:

    var instancePrivate = currentType.GetProperties(BindingFlags.Instance | 
                                                     BindingFlags.NonPublic)
        .Where(x => x.GetMethod.IsPrivate &&
                    x.SetMethod.IsPrivate);
    

    Those are the interesting access modifiers:

    • IsPrivate indicates that the method is private.
    • IsFamily indicates that the method is protected.
    • IsAssembly indicates that the method is internal.

    Other way to elegantly set the filter is using FindMembers:

    public void YourMethod()
    {
        ...
        var instancePrivate = currentType.FindMembers(MemberTypes.Property,
                                                      BindingFlags.Instance |
                                                      BindingFlags.NonPublic,
                                                      PrivateMemberFilter, null);
            .OfType<PropertyInfo>();
        ...
    }
    
    static readonly MemberFilter PrivatePropertyFilter = (objMemberInfo, objSearch) =>
    {
        PropertyInfo info = (objMemberInfo as PropertyInfo);
        if (info == null)
        {
            return false;
        }
        return info.GetMethod.IsPrivate && info.SetMethod.IsPrivate;
    };