Geeks With Blogs

News This is the *old* blog. The new one is at blog.sixeyed.com
Elton Stoneman
This is the *old* blog. The new one is at blog.sixeyed.com

I've never liked having to pass a string to Type.GetInterface() to check if a type implements an interface.

This extension method to the Type class lets you check more neatly with a generic: 

    ///<summary>
    /// Extension methods for the <see cref="Type"/> class.
    ///</summary>
    public static class TypeExtensions
    {
        ///<summary>
        /// Returns whether the type implements the given interface
        ///</summary>
        ///<param name="value"></param>
        ///<returns></returns>
        public static bool ImplementsInterface<T>(this Type type)
        {
            var implements = false;
            if (typeof(T).IsInterface)
            {
                var interfaceName = typeof(T).Name;
                implements = (type.GetInterface(interfaceName) != null);
            }
            return implements;
        }
    }

 Usage:

    Assert.IsTrue(typeof(Stub).ImplementsInterface<IStub>());
Posted on Tuesday, October 4, 2011 10:00 AM Code Snippet | Back to top


Comments on this post: Extension method for neatly checking a type implements an interface

# re: Extension method for neatly checking a type implements an interface
Requesting Gravatar...
The Roslyn Services API makes it easy to implement extensions that detect and fix code issues directly in Visual Studio. The Roslyn Services API is available as part of the Roslyn CTP.
Left by Teamspeak rental on Mar 08, 2012 6:08 AM

# re: Extension method for neatly checking a type implements an interface
Requesting Gravatar...
The blog is absolutely fantastic. Lots of great information and inspiration,
both of which we all need. Thanks.
Left by nedeljni i ljubavni on Oct 18, 2012 9:18 PM

Your comment:
 (will show your gravatar)


Copyright © Elton Stoneman | Powered by: GeeksWithBlogs.net