Let's say, I have a Print method like this:
private static void Print(IEnumerable items)
{
// Print logic here
}
I want to pass a collection class to this Print method, which should print all the fields like a table. For example, my input collection can be "Persons" or "Orders" or "Cars" etc.
If I pass the "Cars" collection to the Print method, it should print the list of "Car" details such as: Make, Color, Price, Class etc.
I won't know the type of the collection until run-time. I tried and achieved a solution using TypeDescriptors
and PropertyDescriptorCollection
. But, I don't feel that is a good solution. Is there any other way to achieve this using expressions or generics?
Override the object's
ToString()
method to include all the information you would like to display, and then simply call it whenever you like. No need for expressions or generics.You could implement Print like this:
It simply loops over each property of the class to print the name of the property, then prints over each item and for each item it prints the values of the properties.
I would argue that you should use generics here (as opposed to suggestions in other answers); you want the items in the collection to be of a single type so that you can print table headers.
For table formatting you can check the answers to this question.
If you don't know what type - i.e. it could be any type - then the best option is to use reflection. That's a good solution. Why do you feel it's not a good solution?
This example caches a Print method for you for performance using Expressions: