Reputation: 27474
In Visual Basic, I want to create an interface that includes a function that returns an object of the implementing class. That is
public interface I
function maker as ???
end interface
public class X
implements I
function maker as X
return new X()
end function
end class
public class Y
implements I
function maker as Y
return new Y()
end function
end class
Is there a way to say that? I suppose I could always say that maker
returns an I
rather than an X
or a Y
, but then callers would have to cast it. I thought of defining the interface as
public interface I(of ii as I)
But the whole point in doing this was so I could create a generic class that uses an of I
, and if I say that, then the compiler insists on an infinite regression of I(of I(of I...
Upvotes: 2
Views: 1856
Reputation: 10931
This is where you need the "curiously recurring" type declaration:
Public Interface I(Of T As I(Of T))
Function Maker() As T
End Interface
Public Class C
Implements I(Of C)
Function Maker() As C Implements I(Of C).Maker
Return New C
End Function
End Class
Sub Main
Dim First As I(Of C) = New C
Dim Second As C = First.Maker
End Sub
As Steven says, this still doesn't force the declaring type to use itself as T
, but at least now T
definitely implements I
.
Upvotes: 0
Reputation: 43743
Not exactly, but you can do this:
Public Interface I(Of T)
Function Maker() As T
End Interface
Public Class X
Implements I(Of X)
Public Function Maker() As X Implements I.Maker
Return New X()
End Function
End Class
Or, like this:
Public Interface I
Function Maker() As I
End Interface
Public Class X
Implements I
Public Function Maker() As I
Return New X()
End Function
End Class
Neither of these options force the derived class to return an instance of their own type, but they allow you to implement it that way.
Upvotes: 2