VB .NET • Use Reflection to Match the Items Parameter

Listing 2. You can use reflection to match the items parameter to a generic List, where each of the members of items is As Person. Next, match an overloaded method's constraints and invoke the method.

Sub ProcessPeople(ByVal items As Object) 'As Boolean

	Dim typ As Type = FindGenericImplementation( _
		items.GetType, GetType(IEnumerable(Of )))

	If typ Is Nothing OrElse _
		Not GetType(Person).IsAssignableFrom( _
		typ.GetGenericArguments(0)) Then
		Throw New InvalidCastException( _
			"unable to cast items to IEnumerable(Of T)")
	End If

	Dim members() As MemberInfo
	members = Me.GetType.GetMember(ProcessPeople", _
		BindingFlags.InvokeMethod Or _ 
		BindingFlags.Instance Or _

	Dim args() As Type = typ.GetGenericArguments
	Dim i As Int32 = 0

	While i < members.Length

	Dim method As MethodInfo = CType(members(i), _

		If Not method.IsGenericMethodDefinition Then
			Continue While
		End If

	Dim methodArgs() As Type = _

		If methodArgs.Length <> args.Length Then
			Continue While
		End If

		For j As Int32 = 0 To args.Length - 1
			Dim constraints() As Type = _ 
			For Each con As Type In constraints
				If Not con.IsAssignableFrom(args(i)) Then
					Continue While
				End If

		method.MakeGenericMethod(args).Invoke( _ 
			Me, New Object() {items})

		Exit Sub
		i += 1
	End While

	Throw New ArgumentException( _
		"type should be IEnumerable")

End Sub