Getting private field or property from object

Yesterday I was playing with finding all UpdatePanel controls on page during 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 to extension methods for Object type, for getting private field an private property. It’s pretty straightforward, besides one thing: since member is private. And we don’t know in witch type exactly (every type in base/descendant hierarchy have it’s one private members) we have to search them all. So this is 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;
            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;
        }
    }

Leave a Reply

Your email address will not be published. Required fields are marked *

Solve : *
24 + 6 =