If I have a predefined object in C#, how can I loop through the object’s structure using reflection to print so it looks like the following:
Class PurchaseOrder
------------------
Property: ID | Type: Int32
Property: Client | Type: Some.Namespace.Client
+---- Property: FirstName | Type: String
+---- Property: LastName | Type: String
+---- Property: Address | Type: Some.Namespace.Address
+---- +---- Property: Line1 | Type: String
Property: Date | Type: DateTime
I want to recurse through the structure of the object (not caring about the actual data inside, but only the name of the property and a type). Additionally, if it’s not a base type, keep recursing down the tree (i.e. an object or a list).
NOTE: Only public members…
I can’t seem to picture this for some reason.
Here’s what the C# classes would look like for the above printed tree:
class PurchaseOrder {
public Int32 Id {get;set;}
public Client Client {get;set;}
public DateTime Date {get;set;}
}
class Client {
public string FirstName {get;set;}
public string LastName {get;set;}
public Address Address {get;set}
}
class Address {
public string Line1 {get;set;}
....
}
However, ideally this would work for any type.
Thanks in advance for your help 🙂
It would be very easy to do it using ObjectDumper.
It’s an opensource tool written by Microsoft that seem to do exactly what you want : write a textual/readable representation of an object properties. It’s a simple class that is very easy to modify if you want to adapt the outpout format.
Simplest usage example:
Check this page for usage samples.