views:

229

answers:

2

VB.Net2005

Simplified Code:

 MustInherit Class InnerBase(Of Inheritor)
End Class

MustInherit Class OuterBase(Of Inheritor)
    Class Inner
        Inherits InnerBase(Of Inner)
    End Class
End Class

Class ChildClass
    Inherits OuterBase(Of ChildClass)
End Class

Class ChildClassTwo
    Inherits OuterBase(Of ChildClassTwo)
End Class

MustInherit Class CollectionClass(Of _
        Inheritor As CollectionClass(Of Inheritor, Member), _
        Member As OuterBase(Of Member))
    Dim fails As Member.Inner ' Type parameter cannot be used as qualifier
    Dim works As New ChildClass.Inner
    Dim failsAsExpected As ChildClassTwo.Inner = works ' type conversion failure
End Class

The error message on the "fails" line is in the subject, and "Member.Inner" is highlighted. Incidentally, the same error occurs with trying to call a shared method of OuterBase.

The "works" line works, but there are a dozen (and counting) ChildClass classes in real life.

The "failsAsExpected" line is there to show that, with generics, each ChildClass has its own distinct Inner class.

My question: is there a way to get a variable, in class CollectionClass, defined as type Member.Inner? what's the critical difference that the compiler can't follow?

(I was eventually able to generate an object by creating a dummy object of type param and calling a method defined in OuterBase. Not the cleanest approach.)

Edit 2008/12/2 altered code to make the two "base" classes generic.

+1  A: 
Dim succeeds as OuterBase.Inner

.net does not have C++'s combination of template classes and typedefs, which means what you are trying to do is not possible, nor does it even make sense in .net.

Justice
+1  A: 

ChildClass.Inner and SomeOtherChildClass.Inner are the same type. Here's a short but complete program to demonstrate:

Imports System

MustInherit Class InnerBase
End Class

MustInherit Class OuterBase
   Class Inner
      Inherits InnerBase
   End Class
End Class

Class ChildClass
   Inherits OuterBase
End Class

Class OtherChildClass
   Inherits OuterBase
End Class

Class Test
    Shared Sub Main()
        Dim x as new ChildClass.Inner
        Dim y as new OtherChildClass.Inner

        Console.WriteLine(x.GetType())
        Console.WriteLine(y.GetType())
    End Sub
End Class

The output is:

OuterBase+Inner
OuterBase+Inner

What were you trying to achieve by using "parameterised" nested classes? I suspect that either it wouldn't work how you'd want it to, or you can achieve it just by using OuterBase.Inner to start with.

Now if each of your child classes were declaring their own nested class, that would be a different situation - and one which generics wouldn't help you with.

Jon Skeet
Of course, you're right. Somehow, I misread the code thinking OuterBase was generic - making ChildClass:OuterBase<T> + InnerClass different than OtherChildClass:OuterBase<S> + InnerClass.
Mark Brackett