Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Getting Private Field or Property from Object

0.00/5 (No votes)
18 May 2013CPOL 6.2K  
How to get private field or property from object

Introduction

Yesterday, I was playing with finding all UpdatePanel controls on page while generating response in ASP.NET. Since object with this information is private itself and collection of panels is private in that object, I had to write some code to extract that data. I ended up with two extension methods for Object type, for getting private field and private property. It's pretty straightforward, besides one thing: since member is private. And we don't know in which type exactly (every type in base/descendent hierarchy has its own private members), we have to search them all.

So this is the final code:

C#
public static class ObjectExtensions
{
    public static TRet GetNonPublicField<TRet>(this object o, string fieldName)
    {
        var bindingFlags = BindingFlags.NonPublic |
        BindingFlags.Instance | BindingFlags.GetField;
        return (TRet)IterateTypesForMember(o, fieldName, bindingFlags);
    }

    public static TRet GetNonPublicProperty<TRet>
    (this object o, string propertyName)
    {
        var bindingFlags = BindingFlags.NonPublic |
        BindingFlags.Instance | BindingFlags.GetProperty;
        return (TRet)IterateTypesForMember(o, propertyName, bindingFlags);
    }

    private static object IterateTypesForMember
    (object o, string memberName, BindingFlags bindingFlags)
    {
        Type type = o.GetType();
        MemberInfo[] memberInfo;
        do
        {
            memberInfo = type.GetMember(memberName, bindingFlags);
            if (memberInfo.Length == 0)
            {
                type = type.BaseType;
            }
        } while (memberInfo.Length == 0 && type != null);
        var member = type.InvokeMember(memberName, bindingFlags, null, o, null);
        return member;
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)