VB .NET • Find the Generic Implementation

Listing 1. This extension method enables you to find a generic implementation in a type. This helper method can help you find either a generic interface or a generic type definition, depending on what you're looking for.

<Extension()> _
Function FindGenericImplementation( _
	ByVal typeToSearch As Type, _
	ByVal genericToFind As Type) As Type

If genericToFind.IsInterface Then
	Return typeToSearch.GetInterface( _
	While typeToSearch IsNot GetType(Object)
		If typeToSearch.IsGenericType AndAlso _
			typeToSearch.GetGenericTypeDefinition _
			Is genericToFind Then
			Return typeToSearch
		End If
		typeToSearch = typeToSearch.BaseType
	End While
End If
Return Nothing
End Function