views:

141

answers:

3

I want to create a VB.NET generic factory method that creates instances of classes (as a home-grown inversion of control container). If I pass the interface IDoSomething as the generic parameter, I want to return an instance of DoSomething (that implements IDoSomething). I cannot figure out the syntax of the if statement. I want to write something like:

Public Function Build(Of T) as T  
    If T Is IDoSomething then  
        Return New DoSomething()  
    ElseIf T Is IAndSoOn Then  
        Return New AndSoOn()  
    Else  
        Throw New WhatWereYouThinkingException("Bad")  
    End If  
End Sub

But this code does not compile.

+4  A: 
Public Function Build(Of T) As T
  Dim foo As Type = GetType(T)

  If foo Is GetType(IDoSomething) Then
    Return New DoSomething()
  ...
  End If
End Function
whatknott
A: 

Public Function Build(Of T) as T
If T.gettype Is gettype(IDoSomething) then
Return New DoSomething()
ElseIf T.gettype Is gettype(IAndSoOn) Then
Return New AndSoOn()
Else
Throw New WhatWereYouThinkingException("Bad")
End If
End Sub

Drakinfar
A: 

That works. Thanks!