Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PropertyInfo.GetSetMethod(true) not returning method for properties from base class

I have following test program:

public class FooBase
{
  public object Prop {
    get { return null; }
    private set { } 
  }
}
public class Foo :FooBase
{
}
class Program
{
  static void Main(string[] args)
  {
    MethodInfo setMethod = typeof(Foo).GetProperty("Prop").GetSetMethod(true);
    if (setMethod==null)
      Console.WriteLine("NULL");
    else
      Console.WriteLine(setMethod.ToString());
    Console.ReadKey(); 
  }
}

And it shows "NULL" if I run it. If I move property definition to class Foo then I works as expected. Is this a bug in .NET?

like image 278
Denis Bredikhin Avatar asked Jul 02 '11 14:07

Denis Bredikhin


2 Answers

You can achieve it by getting the PropertyInfo on the declaring type of the property, simple extension method could be...

public static class Extensions
{
   public static MethodInfo GetSetMethodOnDeclaringType(this PropertyInfo propertyInfo)
   {
       var methodInfo = propertyInfo.GetSetMethod(true);
       return methodInfo ?? propertyInfo
                               .DeclaringType
                               .GetProperty(propertyInfo.Name)
                               .GetSetMethod(true);
   }
}

then your calling code does...

class Program
{
    static void Main(string[] args)
    {
       MethodInfo setMethod = typeof(Foo)
                                 .GetProperty("Prop")
                                 .GetSetMethodOnDeclaringType();
       if (setMethod == null)
            Console.WriteLine("NULL");
        else
            Console.WriteLine(setMethod.ToString());
         Console.ReadKey();
    }
}
like image 121
Gareth Avatar answered Sep 19 '22 14:09

Gareth


This is by design. The FooBase property setter is not accessible in the Foo class, no matter what you try:

public class Foo : FooBase {
    void Test() {
        Prop = new object();  // No
        ((FooBase)this).Prop = new object();  // No
    }
}

You'll have to use typeof(FooBase).GetProperty("Prop") in your code.

like image 27
Hans Passant Avatar answered Sep 18 '22 14:09

Hans Passant