Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic List / Dictionary

Tags:

c#

generics

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

like image 393
Sascha Avatar asked Oct 15 '22 16:10

Sascha


1 Answers

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);
    }
}
like image 170
Marc Gravell Avatar answered Oct 19 '22 05:10

Marc Gravell