get all interfaces on a type in csharp

In C#, you can use Reflection to retrieve all the interfaces implemented by a given type. Here's an example:

main.cs
using System;
using System.Linq;

class MyClass : IDisposable, ICloneable
{
    public void Dispose() { Console.WriteLine("Dispose"); }
    public object Clone() { Console.WriteLine("Clone"); return null; }
}

class Program
{
    static void Main()
    {
        Type type = typeof(MyClass);
        Type[] interfaces = type.GetInterfaces();

        foreach (Type i in interfaces)
        {
            Console.WriteLine(i.Name);
        }
    }
}
449 chars
23 lines

In this example, we define a class MyClass that implements two interfaces: IDisposable and ICloneable. We then use the typeof operator to get a Type object representing MyClass, and call the GetInterfaces method on that object to get an array of Type objects representing the interfaces implemented by MyClass. We then simply loop through that array and print out the names of each interface.

This will output:

main.cs
IDisposable
ICloneable
23 chars
3 lines

gistlibby LogSnag