Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reflection can't find private setter on property of abstract class

When I have this property in an abstract class:

public IList<Component> Components { get; private set; }

Then when I call:

p.GetSetMethod(true)

with p being a PropertyInfo object pointing to my property, I get null.

However if I change the property setter to protected, I can see it via reflection. Why is this? I don't seem to recall having this problem with non-abstract classes...

like image 764
ekolis Avatar asked Dec 24 '13 16:12

ekolis


1 Answers

The following experimentation uncovered the issue for me. Note that the base class doesn't have to be abstract to reproduce the problem.

public class Base
{
    public string Something { get; private set; }
}

public class Derived : Base { }

public class MiscTest
{
    static void Main( string[] args )
    {
        var property1 = typeof( Derived ).GetProperty( "Something" );
        var setter1 = property1.SetMethod; //null
        var property2 = typeof( Base ).GetProperty( "Something" );
        var setter2 = property2.SetMethod; //non-null

        bool test1 = property1 == property2; //false
        bool test2 = property1.DeclaringType == property2.DeclaringType; //true

        var solution = property1.DeclaringType.GetProperty( property1.Name );
        var setter3 = solution.SetMethod; //non-null
        bool test3 = solution == property1; //false
        bool test4 = solution == property2; //true
        bool test5 = setter3 == setter2; //true
    }
}

What I learned from this and found surprising, is that the PropertyInfo on the derived type is a different instance than the PropertyInfo on the base type. Weird!

like image 152
HappyNomad Avatar answered Nov 15 '22 19:11

HappyNomad