65.9K
CodeProject is changing. Read more.
Home

Getting Private Field or Property from Object

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

May 18, 2013

CPOL
viewsIcon

6172

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:

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