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!

Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

1 comment:

Anonymous said...

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;
}