Reflection and Non-Public Properties

by Kev Ritchie 23. November 2010 11:34

Ever wondered how to get to those Non-Public properties of an object?

With Reflection, here’s how you do it:

object propertyValue = anyObject.GetType().GetProperty("TheProperty", 
BindingFlags.Instance | BindingFlags.NonPublic).GetValue(anyObject, null);

All you need to do is replace “anyObject” with the name of object you are trying to get the Non-Public property from, then change “TheProperty” to the name of the Non-Public property you are trying to access.

A little explanation.

When we call the GetProperty method on a type, we supply some parameters to search the associated object with.

Our first parameter is the name of the property that we’re looking for.  The second parameter; BindingFlags, is a bitmask comprised of one or more BindingFlags that specify how the search is conducted; in really basic terms, a filter.  In the example above, we are specifying a Binding Flag of Instance, this must be specified in order to get a return from the search.  We are then using an “Or” operator to tell the search that we want to include Non-Public properties.

The GetValue method is then called to return the value of the property you were looking for.

Hope this is of some use to someone and if anything else will be a little reminder to myself in case I forget Winking smile

Comments are closed

Powered by BlogEngine.NET
Theme by Mads Kristensen | Modified by Mooglegiant