Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you get the all properties of a class and its base classes (up the hierarchy) with Reflection? (C#)

So what I have right now is something like this:

PropertyInfo[] info = obj.GetType().GetProperties(BindingFlags.Public); 

where obj is some object.

The problem is some of the properties I want aren't in obj.GetType() they're in one of the base classes further up. If I stop the debugger and look at obj, the I have to dig through a few "base" entries to see the properties I want to get at. Is there some binding flag I can set to have it return those or do I have to recursively dig through the Type.BaseType hierarchy and do GetProperties on all of them?

like image 628
Davy8 Avatar asked Oct 28 '08 22:10

Davy8


People also ask

What is the base class for all classes in C #?

The Object class is the base class for all the classes in the . Net Framework. It is present in the System namespace.

What are reflections in C#?

Reflection provides objects (of type Type) that describe assemblies, modules, and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties.

What is GetProperties C#?

GetProperties() Returns all the public properties of the current Type.


2 Answers

Use this:

PropertyInfo[] info = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); 

EDIT: Of course the correct answer is that of Jay. GetProperties() without parameters is equivalent to GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static ). The BindingFlags.FlattenHierarchy plays no role here.

like image 99
Panos Avatar answered Sep 25 '22 06:09

Panos


I don't think it's that complicated.

If you remove the BindingFlags parameter to GetProperties, I think you get the results you're looking for:

    class B     {         public int MyProperty { get; set; }     }      class C : B     {         public string MyProperty2 { get; set; }     }      static void Main(string[] args)     {         PropertyInfo[] info = new C().GetType().GetProperties();         foreach (var pi in info)         {             Console.WriteLine(pi.Name);         }     } 

produces

     MyProperty2     MyProperty 
like image 37
Jay Bazuzi Avatar answered Sep 25 '22 06:09

Jay Bazuzi