Douglas Stockwell's Generics Quiz
Douglas Stockwell posed an interesting problem the other day. He wanted to know if there was a way to make a piece of code work without falling down to reflection.
Personally, I can't see any way to do it without reflection, so I thought I'd post my answers on how to do it with reflection here :)
The problem is like this.
You have to interfaces defined:
Public Interface IA
End Interface
Public Interface IB
End Interface
And you have a generic method that demands a generic type T such that T implements both IA and IB. There's also a situation that takes parameter of type IA.
Public Class SomeClass
Sub AandB(Of T As {IA, IB})(ByVal anb As T)
MsgBox("here i am")
End Sub
Sub Situation(ByVal a As IA)
If TypeOf a Is IB Then
'call AandB() here somehow.
End If
End Sub
End Class
So the question was: How do you call AandB() passing in the parameter 'a' from Situation()?
At first glance it's easy, but it's actually not. I put the code into visual studio thinking it would be a cinch, but then moment I actually tried to call AandB() it all broke :)
Using reflection however it's quite simple.
Public Class SomeClass
Sub AandB(Of T As {IA, IB})(ByVal anb As T)
MsgBox("here i am")
End Sub
Sub Situation(ByVal a As IA)
If TypeOf a Is IB Then
Dim paramType As System.Type = CObj(a).GetType()
Dim classType As System.Type = GetType(SomeClass)
Dim method As System.Reflection.MethodInfo = classType.GetMethod("AandB", _
Reflection.BindingFlags.Public _
Or Reflection.BindingFlags.Instance _
Or Reflection.BindingFlags.DeclaredOnly)
Dim genericMethod As System.Reflection.MethodInfo = method.MakeGenericMethod(paramType)
genericMethod.Invoke(Me, New Object() {a})
End If
End Sub
End Class
There's obviously no error checking going on (which you really should have) but it works.