Determine if an object implements IEnumerable of (T)

I was recently attending a .NET conference when a programmer popped up a question. How do I make sure that my type implements IEnumerable<T>

Here's how:

C#


    protected void CheckInterfaceImpl(Type someType)


    {


        Type[] listInterfaces = someType.GetType().GetInterfaces();


        foreach (Type t in listInterfaces)


        {


            if (t.GetGenericTypeDefinition() == typeof(IEnumerable<>))   


            {       


                // Implements IEnumerable<T>


            }


            else


            {


                // Does not Implement IEnumerable<T>


            }


 


        }


    }




VB.NET


    Protected Sub CheckInterfaceImpl(ByVal someType As Type)


        Dim listInterfaces() As Type = someType.GetType.GetInterfaces()


        For Each t As Type In listInterfaces


            If t.GetGenericTypeDefinition() Is GetType(IEnumerable(Of )) Then


                ' Implements IEnumerable<T>


            Else


                ' Does not Implement IEnumerable<T>


            End If


 


        Next t


    End Sub




Know a better way? Share it here. I am all ears!

1 comment:

  1. This code does not work at all.
    1. someType.GetType() returns typeof(Type).
    2. GetGenericTypeDefinition() is only valid for generic types, it will throw InvalidOpertaionException as soon as it reaches first non-generic interface.

    Here is my solution (C#):

    static bool IsIEnumerableT (Type someType)
    {
    return someType.GetInterface (typeof(IEnumerable<>).FullName) != null;
    }

    ReplyDelete