Generic Sub Classes

written by Ryan Olshan on Monday, January 02 2006

In generics, you can use sub classes just as you would any non-generic sub class. Take the following class and sub class for example:

VB.NET
Public Class OuterClass(Of T, U, V)
   Public Class InnerClass(Of T, U)
      Public Function InnerMethod(ByVal val1 As T, ByVal val2 As U) As V
         ' Some code here
      End Function
   End Class
End Class

C#
public class OuterClass<T, U, V>
{
   public class InnerClass<T, U>
   {
      public V InnerMethod(T val1, U val2)
      {
         // Some code here
      }
   }
}

The above code is perfectly legal and will compile. The question is which class will T and U in InnerMethod inherit its type references from? The answer is the class which the method is contained in, in the case of the example provided above, InnerClass. However, you should never name the types of a sub class the same as those of the class it is contained in. If you get in the habbit of using strongly named types, you will avoid possible future problems.

Kick this post on .NET Kicks

Similar Posts

  1. Generic Type Inference
  2. What's wrong with this generic type?
  3. What's wrong with this generic class?

Post a comment