How to determine if a type implements an interface with C# reflection
You have a few choices:
typeof(IMyInterface).IsAssignableFrom(typeof(MyType))
typeof(MyType).GetInterfaces().Contains(typeof(IMyInterface))
- 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<>))
C# How to determine if a type implements a given interface?
You can use IsAssignableFrom
bool IsDisposable = typeof(IDisposable).IsAssignableFrom(typeof(TextWriter));
DEMO
Test if object implements interface
if (object is IBlah)
or
IBlah myTest = originalObject as IBlah
if (myTest != null)
How to determine if a type implements a specific generic interface type
By using the answer from TcKs it can also be done with the following LINQ query:
bool isBar = foo.GetType().GetInterfaces().Any(x =>
x.IsGenericType &&
x.GetGenericTypeDefinition() == typeof(IBar<>));
How to determine dynamically if type is an Interface using reflection?
You can use Type.IsInterface
Property
https://msdn.microsoft.com/en-us/library/system.type.isinterface(v=vs.110).aspx
How to see if a type implements an interface?
TypeOf ... Is
works fine with inheritance:
Imports System
Public Class Test
Public Shared Sub Main()
Dim o As Object = 5
If TypeOf o Is IFormattable Then
Console.WriteLine("Yes")
End If
End Sub
End Class
That works the same way as "is" in C#.
However, in your example, that's trying to see whether System.Type
(or whatever subclass is actually used) implements Rule.IRule
. That won't work... because you're not interested in whether System.Type
implements the interface, you're interested in whether the instance of System.Type
that the typeAsm
variable refers to implements IRule.Rule
.
In other words, your code wouldn't have worked any better in C# either. You need Type.IsAssignableFrom
when talking about an instance of System.Type
:
If GetType(Rule.IRule).IsAssignableFrom(typeAsm) Then
Getting all types that implement an interface
Mine would be this in c# 3.0 :)
var type = typeof(IMyInterface);
var types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.Where(p => type.IsAssignableFrom(p));
Basically, the least amount of iterations will always be:
loop assemblies
loop types
see if implemented.
Check if object implements specific generic interface
Simply us the is
or as
operator:
if( this is IHandleEvent<Event1> )
....
Or, if the type argument isn't known at compile time:
var t = typeof( IHandleEvent<> ).MakeGenericType( /* any type here */ )
if( t.IsAssignableFrom( this.GetType() )
....
Use Reflection to Find Interface T in Assembly Types
As mentioned in the comments, have to use the Type.MakeGenericType
method to create the needed type IDataService<"T">
at runtime. Your Get
method could look like this:
private static object Get(Type t)
{
var types = typeof(CrewRepository).Assembly.GetTypes();
var runtimeType = typeof(IDataService<>).MakeGenericType(t);
var type = types.SingleOrDefault(x => x.GetInterfaces().Contains(runtimeType));
if (type != null)
{
return Activator.CreateInstance(type, _context);
}
return null;
}
Demo: https://dotnetfiddle.net/vRJzr8
Related Topics
How to Format a Number into a String with Leading Zeros
Linq Select Distinct with Anonymous Types
How to Build a Datatemplate in C# Code
Why Should I Use Int Instead of a Byte or Short in C#
Listen to Changes of Dependency Property
Capture Screenshot Including Semitransparent Windows in .Net
Servicestack Rest API and Cors
How to Loop Through Ienumerable in Batches
What Is the Equivalent of Memset in C#
Convert JSON String to JSON Object C#
Read Post Data Submitted to ASP.NET Form
Can a C# Class Inherit Attributes from Its Interface
What's the Difference Between Bitmap.Clone() and New Bitmap(Bitmap)
Convert Comma Separated String of Ints to Int Array
Playing a Mp3 File in a Winform Application
Access to the Path Is Denied When Using Directory.Getfiles(...)