Wednesday, October 14, 2009

How to use reflection to look for property that implements IList (or any other) iterface

In this sample I have created a function that gets a class of type T and inspects properties to find IList implementation.

Public Function GetResponse(Of T)(ByVal instance As T) As IList
    Dim props As PropertyInfo() = instance.GetType.GetProperties(BindingFlags.Public Or BindingFlags.Instance)
    For Each p In props
      If GetType(IList).IsAssignableFrom(p.PropertyType) AndAlso p.PropertyType.IsGenericType Then
        Dim listItems As IList = DirectCast(p.GetValue(instance, Nothing), IList)
        If listItems IsNot Nothing Then
          Return listItems
        End If
      End If

    Return Nothing
  End Function

No comments: