Click here to Skip to main content
13,289,439 members (65,482 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


4 bookmarked
Posted 18 May 2013

Getting Private Field or Property from Object

, 18 May 2013
Rate this:
Please Sign up or sign in to vote.
How to get private field or property from object


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:

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;
            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;


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


About the Author

Software Developer
Poland Poland
No Biography provided

You may also be interested in...


Comments and Discussions

-- There are no messages in this forum --
Permalink | Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.171207.1 | Last Updated 18 May 2013
Article Copyright 2013 by n.podbielski
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid