Jun 02
Given two generic classes:
public class Type1<T> {} public class Type2<T> {}
.NET allows you to specify a generic type as the type of another generic type:
Type1<Type2<int>> obj = new Type1<Type2<int>>();
Simple Example
Consider a simple reference class that might be used for lazy-fetching an object. For simplicity, the lazy-fetching code has been removed:
public class Ref<T> { public Ref() { } public Ref( T val ) { this.Value = val; } public T Value; public override string ToString() { return this.Value.ToString(); } }
It’s possible to store this generic type Ref<T> in a List<T>, which is also a generic type.
Here’s a sample console program to demonstrate this:
static void Main( string[] args ) { List<Ref<int>> refIntList = new List<Ref<int>>(); refIntList.Add( new Ref<int>( 6 ) ); refIntList.Add( new Ref<int>( 7 ) ); foreach (Ref<int> refInt in refIntList) { Console.WriteLine( refInt ); } List<Ref<string>> refStringList = new List<Ref<string>>(); refStringList.Add( new Ref<string>( "six" ) ); refStringList.Add( new Ref<string>( "seven" ) ); foreach (Ref<string> refString in refStringList) { Console.WriteLine( refString ); } Console.ReadLine(); }
As you would expect, the console output is:
6
7
six
seven
[…] Nested Generics – Tim M […]
Nested types are much easier to accomplish if you inherit from a collection base, then expose a property from the new type which is of the same type as the new type. e.g.
public class SomeCollection : ICollection
{
public SomeCollection Children{get;set;}
}
Found one another implementation at
http://cinchoo.wordpress.com/2012/01/07/cinchoo-collections-nestedlist-part-1/
Sounds simple and elegant.