I wrote a method that accepts a generic parameter and then it prints its properties. I use it to test my web service. It's working but I want to add some features that I don't know how to implement. I want to print values of lists, because now it just writes System.Collection.Generic.List1 which is expected.
Here is my code so far, this is working for basic types (int, double etc.):
static void printReturnedProperties<T>(T Object)
{
PropertyInfo[] propertyInfos = null;
propertyInfos = Object.GetType().GetProperties();
foreach (var item in propertyInfos)
Console.WriteLine(item.Name + ": " + item.GetValue(Object).ToString());
}
Here is a snippet, assuming that your List is of Type T.
You could do something like this:
It will then enumerate through any IEnumerable and print out the individual values (I'm printing them one per line, but obviously, you can do different.)
The elements inside a list can be retrieved through the indexer property
Item
. This property accepts an index argument (there is an overload ofPropertyInfo.GetValue
that accept anobject
array, just likeMethodInfo.Invoke
) and returns the object at that position.I think you want something like this:
The code is untested but basically, you want to tackle enumerable types differently as compared to scalar values, so once you hit something of the type
IEnumerable<TItemType>
, you make a call to theFormatList<TPlaceholder>
method.Now, bear in mind that your original
T
andTItemType
are not necessarily the same. When you invoke FormatList using reflection, you want to bind theTPlaceholder
toTItemType
. Once you have done that, you just invoke the formatting method and pass it the actual instance of the list, which returns you a string. That string you can then just output.Hope that helps.
Borrowing heavily on the above examples, here is my full solution. This has been tested and handles IEnumerable's being passed in by printing out the properties of each element. It's not recursive but that's easy enough to add.
Be aware that many of the above examples will crash with indexed properties (lists for example). Parameter count mismatch in property.GetValue().
It's avoided here by filtering properties which have indexed properties using this bit of LINQ.
Full example in the form of an extension method below.
I usually prints list with a
,
between each item.To make that easy I have created a simple extension method:
Call the method as
myList.StringJoin()
.You can of course modify the method to use another delimiter och call
string.Join
directly.