tags:

views:

435

answers:

1

Is it possible to define a generic type in C# that references itself?

E.g. I want to define a Dictionary<> that holds its type as TValue (for a hierarchy).

Dictionary<string, Dictionary<string, Dictionary<string, [...]>>>
+12  A: 

Try:

class StringToDictionary : Dictionary<string, StringToDictionary> { }

Then you can write:

var stuff = new StringToDictionary
        {
            { "Fruit", new StringToDictionary
                {
                    { "Apple", null },
                    { "Banana", null },
                    { "Lemon", new StringToDictionary { { "Sharp", null } } }
                }
            },
        };

General principle for recursion: find some way to give a name to the rescursive pattern, so it can refer to itself by name.

Daniel Earwicker
+1 very nice, that actually compiles/runs
eglasius
thanks! good that Dictionary isn't sealed :)
chris