Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GetFields returning empty array

Tags:

c#

reflection

Can anyone see what I am doing wrong below? The type has the public property that the service method is trying to access so why is it not being picked up by reflection?

Public class SomeClass
{
   private YetAnotherClass yetAnotherClass;

   public SomeClass(SomeOtherClass otherclass)
   {
       this.yetAnotherClass = otherclass.SomeProperty;
   }

   public YetAnotherClass SomeProperty
   {
       get { return this.yetAnotherClass; }
   }
}

Public class ServiceClass
{
    public void DoSomething(SomeClass someclass)
    {
         Type type = someclass.GetType();
         FieldInfo[] fieldsinfo = type.GetFields(BindingFlags.Public | BindingFlags.Instance); // returns empty collection
         FieldInfo fieldinfo = type.GetField("SomeProperty"); // returns null reference exception
    }
}

Cheers

Stewart

like image 698
Stewart Alan Avatar asked Sep 18 '26 05:09

Stewart Alan


1 Answers

SomeProperty is - as the name says - a property. Use GetProperty and GetProperties instead! That leads to PropertyInfo instead of FieldInfo.

like image 67
Sebastian Avatar answered Sep 19 '26 18:09

Sebastian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!