interface reflection

In this chapter you will learn:

  1. How to get interfaces from Type
  2. static and dynamic interface type checking
  3. Get all implemented interface and their methods

Get interfaces

The GetInterfaces method returns the interfaces that a type implements:

using System;/*from j av a 2s.co  m*/
using System.Reflection;
using System.Collections.Generic;

class MainClass
{
    static void Main()
    {
        foreach (Type iType in typeof(Guid).GetInterfaces())
            Console.WriteLine(iType.Name);

    }

}

The output:

static and dynamic interface type checking

The following code does the static and dynamic interface type checking.

using System;//from  j av  a2  s. c  o  m
using System.Reflection;
using System.Collections.Generic;

class MainClass
{
    static void Main()
    {
        Type target = typeof(IFormattable);

        bool isTrue = target is IFormattable; // Static C# operator 
        bool alsoTrue = target.IsInstanceOfType(target);  // Dynamic equivalent
    }

}

Get all implemented interface and their methods

using System;//from  ja  va  2  s  .  c om
using System.Reflection;

public interface IFaceOne
{
  void MethodA();
}

public interface IFaceTwo
{
  void MethodB();
}

public class MyClass: IFaceOne, IFaceTwo
{
  public enum MyNestedEnum{}
  
  public int myIntField;
  public string myStringField;

  public void myMethod(int p1, string p2)
  {
  }

  public int MyProp
  {
    get { return myIntField; }
    set { myIntField = value; }
  }

  void IFaceOne.MethodA(){}
  void IFaceTwo.MethodB(){}
}

public class MainClass
{
  public static void Main(string[] args)
  {
    MyClass f = new MyClass();

    Type t = f.GetType();
    
    Type[] iFaces = t.GetInterfaces();

    for(int i = 0; i < iFaces.Length; i ++)
    {
      Console.WriteLine("Info on Interface named: {0}", iFaces[i]);

      MethodInfo[] classMethodNames = t.GetInterfaceMap(iFaces[i]).TargetMethods;
      MethodInfo[] interfaceMethodNames = t.GetInterfaceMap(iFaces[i]).InterfaceMethods;

    }
  }
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. Open and constructed generic types
  2. Getting generic type definition information
  3. Dynamically constructing types
  4. Closed generic type
Home » C# Tutorial » Reflection
Reflection
Type
Type properties
Field reflection
Field Type
Field Attributes
FieldHandle
Field value
Set Field value
delegate reflection
Event reflection
Indexer reflection
Properties Reflection
Method
Parameter
Invoke
Type Instantiating
interface reflection
Generic type reflection
Reflection on nested Types
Subtype
Array reflection
Assembly