Skip to content

Instantly share code, notes, and snippets.

@chilversc
Created March 24, 2010 20:30
Show Gist options
  • Save chilversc/342750 to your computer and use it in GitHub Desktop.
Save chilversc/342750 to your computer and use it in GitHub Desktop.
Rough implementation to find a concrete list type from an interface
Sub Main
Dim type = GetType(List(Of String))
FindExplicitListType(type).Dump()
End Sub
Function FindExplicitListType(type As Type) As Type
If type.IsClass Then
'TODO: Should check if type implements IList or IList(Of)
Return type
ElseIf IsGenericList(type)
Return GetExplicitListType(type)
Else
Dim found = type.GetInterfaces().Where(AddressOf IsGenericList).ToList()
If found.Count <> 1
'TODO: Some sort of error
End If
Return GetExplicitListType(found(0))
End If
'TODO: Should check if it implements more than one list type
'TODO: Should check if it implements IList
'TODO: Should check if it is an array
End Function
Function IsGenericList(type As Type) As Boolean
Return type.IsGenericType() AndAlso GetType(IList(Of)) Is type.GetGenericTypeDefinition()
End Function
Function GetExplicitListType(type As Type) As Type
'Assumes IsGenericList(type) returns true
Dim elementType = type.GetGenericArguments()(0)
Return GetType(List(Of)).MakeGenericType(elementType)
End Function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment