Pages

Friday, November 25, 2011

Nested Generics

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

No comments:

Post a Comment