tags:

views:

327

answers:

1

Hi,

I'm trying to output an object graph via reflection. In it there are several generic types (lists, dictionaries). I do not know the types (string, object, etc.) they contain but want to list them (using .ToString()).

So, is there a way to output a generic list / dictionary in generic way, that means without writing overloaded functions for each key <-> value combintation?

I think it will be possible with .NET 4.0, but that's currently not yet here..

+2  A: 

If you are using reflection, generics gets very tricky. Can you simply use the non-generic interfaces? IDictionary/IList? It would be a lot easier... something like:

static void Write(object obj) {
    if (obj == null) { }
    else if (obj is IDictionary) { Write((IDictionary)obj); }
    else if (obj is IList) { Write((IList)obj); }
    else { Console.WriteLine(obj); }
}
static void Write(IList data) {
    foreach (object obj in data) {
        Console.WriteLine(obj);
    }
}
static void Write(IDictionary data) {
    foreach (DictionaryEntry entry in data) {
        Console.WriteLine(entry.Key + "=" + entry.Value);
    }
}
Marc Gravell
A classic case of thinking too complex. A generic list is assignable to IList, so I just need to figure out if it's a list or a dictionary. Thanks.
Sascha
Actually, neither is automatically convertible; it is not true that IList<T> : IList, not that IDictionary<TKey,TValue> : IDictionary - but most implementations provide both.
Marc Gravell