Click here to Skip to main content
Click here to Skip to main content
Technical Blog

Tagged as

Getting Private Field or Property from Object

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

Introduction

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

License

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

Share

About the Author

n.podbielski
Software Developer
Poland Poland
No Biography provided

Comments and Discussions

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