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);
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.
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.
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.
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.
You have a few choices:
typeof(IMyInterface).IsAssignableFrom(typeof(MyType))
typeof(MyType).GetInterfaces().Contains(typeof(IMyInterface))
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<>))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With