Tuesday, January 08, 2008

Referencing type within a generic class

In the following code snippet, an enum class1Enum type is declared with in a generic class Class1<T>. In order to reference to class1Enum type, we have to instantiate the generic class by supplying its type as shown in the declaration of var1 and var2. Another catch is that, although the var1 and var2 are of the same class1Enum type, they are declared in  different classes namely  Class1<int> and Class1<string>, and therefore they are not the same.

    public class Class1<T>
    {
         public T t;
 
        public enum  class1Enum
        {
            a,
            b
        }
     }
 
    public class Class2
     {
        public Class1.class1Enum var; // compile error
 
         public Class1<int>.class1Enum var1;
         public Class1<string>.class1Enum var2;
  
        public Class2()
        {
            var1 = var2; // compile error 
        }
    }

No comments: