Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if a type implements an interface with C# reflection

Does reflection in C# offer a way to determine if some given System.Type type models some interface?

public interface IMyInterface {}  public class MyType : IMyInterface {}  // should yield 'true' typeof(MyType)./* ????? */MODELS_INTERFACE(IMyInterface); 
like image 869
Yippie-Ki-Yay Avatar asked Feb 10 '11 21:02

Yippie-Ki-Yay


People also ask

How do you check if an object implements an interface?

Use a user-defined type guard to check if an object implements an interface in TypeScript. The user-defined type guard consists of a function, which checks if the passed in object contains specific properties and returns a type predicate.

What type is an interface C#?

Interfaces summary In C# versions earlier than 8.0, an interface is like an abstract base class with only abstract members. A class or struct that implements the interface must implement all its members. Beginning with C# 8.0, an interface may define default implementations for some or all of its members.

Does class implement interface C#?

The implementation of the interface's members will be given by class who implements the interface implicitly or explicitly. Interfaces specify what a class must do and not how. Interfaces can't have private members. By default all the members of Interface are public and abstract.

How do you know when to use an interface?

You should use an interface if you want a contract on some behavior or functionality. You should not use an interface if you need to write the same code for the interface methods. In this case, you should use an abstract class, define the method once, and reuse it as needed.


1 Answers

You have a few choices:

  1. typeof(IMyInterface).IsAssignableFrom(typeof(MyType))
  2. typeof(MyType).GetInterfaces().Contains(typeof(IMyInterface))
  3. With C# 6 you can use typeof(MyType).GetInterface(nameof(IMyInterface)) != null

For a generic interface, it’s a bit different.

typeof(MyType).GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IMyInterface<>)) 
like image 88
Jeff Avatar answered Sep 19 '22 18:09

Jeff