I’m trying to make a very rudimentary generic object printer for debugging, inspired by the awesomeness you get in LinqPad.
Below is the pseudocode for my print function. My reflection-foo is kind of weak at the moment and I’m struggling to deal with the case when the object is an ILookup, as I’d like enumerate the lookup, printing each key alongside its associated collection.
ILookup doesn’t have a non-generic interface and it doesn’t implement IDictionary, so I’m kind of stuck at the moment, as I can’t say o as ILookup<object,object>… For that matter, I’d like to know how to delve into any generic interface…suppose I’d like to have a special case for CustomObject<,,>.
void Print(object o)
{
if(o == null || o.GetType().IsValueType || o is string)
{
Console.WriteLine(o ?? "*nil*");
return;
}
var dict = o as IDictionary;
if(dict != null)
{
foreach(var key in (o as IDictionary).Keys)
{
var value = dict[key];
Print(key + " " + value);
}
return;
}
//how can i make it work with an ILookup?
//?????????
var coll = o as IEnumerable;
if(coll != null)
{
foreach(var item in coll)
{ print(item); }
return;
}
//else it's some object, reflect the properties+values
{
//reflectiony stuff
}
}
I’m not sure what you’re trying to accomplish exactly, but to answer your specific question, you can use reflection like this:
I’ve tried to write it in such a way that you can write the printing logic in a strongly-typed manner with generics. If you prefer, you can instead do even more reflection to get the key and values out of each
IGrouping<,>in the lookup.EDIT: By the way, if you are on C# 4, you can replace the entire body of the
ifstatement with: