Sascha
Sascha

Reputation: 10347

Generic List / Dictionary

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..

Upvotes: 5

Views: 1222

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062745

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);
    }
}

Upvotes: 4

Related Questions