jQuery and ASP.NET

March 18, 2009

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!

'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

1 Response to "Determine if an object implements IEnumerable of (T)"
  1. Anonymous said...
    May 21, 2011 3:34 AM

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

 

Copyright © 2009-2011 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions