ivvi
ivvi

Reputation: 5310

Can't access protected property with Reflection

While debugging at a break point, I'm unable to access the property Rectangle_1 (and other sibling properties), using Reflection, that are visible in a watch window.

watch window

In the Immediate Window, If I try

typeof(LoadRecipeSlots).GetProperty("Rectangle_1")

the result is null.

but if I try

typeof(LoadRecipeSlots).GetProperty("Visible")

the result is

{Boolean Visible}
Attributes: None
CanRead: true
CanWrite: true
CustomAttributes: Count = 1
DeclaringType: DeclaredProperties = {System.Reflection.PropertyInfo[65]}
GetMethod: {Boolean get_Visible()}
IsSpecialName: false
MemberType: Property
MetadataToken: 385877353
Module: {ControlsCF.dll}
Name: "Visible"
PropertyType: DeclaredProperties = {System.Reflection.PropertyInfo[0]}
ReflectedType: DeclaredProperties = {System.Reflection.PropertyInfo[7]}
SetMethod: {Void set_Visible(Boolean)}

The property Visible seems to be a property of a parent class.

The property Rectangle_1 is protected in LoadRecipeSlots and I'm trying to use Reflection to access it from a partial class definition, which I'm unable to do. The property is however accessible as code in this partial class definition.

Most of the code is auto-generated by the tool in use, iX Developer, so I'm not able to create a concise example. If something is missing, let me know, and I'll try to add it to the question.

Upvotes: 0

Views: 1156

Answers (2)

Garrison Becker
Garrison Becker

Reputation: 482

It's because the property you're wanting to access is protected (not public) and GetProperty(String) by default only returns public properties.

You can use GetProperty(String, BindingFlags) like below to retrieve your protected property:

typeof(LoadRecipeSlots).GetProperty("Rectangle_1", BindingFlags.NonPublic)

Upvotes: 1

Klaus Gütter
Klaus Gütter

Reputation: 12032

typeof(LoadRecipeSlots).GetProperty("Rectangle_1")

will search only public properties. As your property is protected, you need to specify that also non-public properties shall be searched:

typeof(LoadRecipeSlots).GetProperty("Rectangle_1", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)

Upvotes: 2

Related Questions