O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

7.7. An Advanced Interface Search Mechanism

Problem

You are searching for an interface using the Type class. However, complex interface searches are not available through the GetInterface and GetInterfaces methods of a Type object. The GetInterface method searches for an interface only by name (using a case-sensitive or -insensitive search), and the GetInterfaces method returns an array of all the interfaces implemented on a particular type. You want a more focused searching mechanism that might involve searching for interfaces that define a method with a specific signature or implemented interfaces that are loaded from the Global Assembly Cache (GAC). You need more flexible and more advanced searching for interfaces that does not involve creating your own interface search engine.

Solution

The FindInterfaces method of a Type object can be used along with a callback to perform complex searches of interfaces on a type. The following method will call a custom interface searching method, SearchInterfacesOfType:

using System; using System.Reflection; public class SearchType { public void FindSpecificInterfaces( ) { Type[] names = new Type[3] {Type.GetType("System.ICloneable"), Type.GetType("System.Collections.ICollection"), Type.GetType("System.IAppDomainSetup")}; Type[] interfaces = SearchInterfacesOfType(Type.GetType( "System.Collections.ArrayList"), names); if (interfaces.Length > 0) { Console.WriteLine("Matches found:"); for(int counter =0; counter < interfaces.Length; counter++) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required