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<>));
Finding out if a type implements a generic interface
// this conditional is necessary if myType can be an interface,
// because an interface doesn't implement itself: for example,
// typeof (IList<int>).GetInterfaces () does not contain IList<int>!
if (myType.IsInterface && myType.IsGenericType &&
myType.GetGenericTypeDefinition () == typeof (IList<>))
return myType.GetGenericArguments ()[0] ;
foreach (var i in myType.GetInterfaces ())
if (i.IsGenericType && i.GetGenericTypeDefinition () == typeof (IList<>))
return i.GetGenericArguments ()[0] ;
Edit: Even if myType
implements IDerivedFromList<>
but not directly IList<>
, IList<>
will show up in the array returned by GetInterfaces()
.
Update: added a check for the edge case where myType
is the generic interface in question.
Check if a type implements a generic interface without considering the generic type arguments
As far as I know, the only way to do this is to get all interfaces and see if the generic definition matches the required interface type.
bool result1 = type.GetInterfaces()
.Where(i => i.IsGenericType)
.Select(i => i.GetGenericTypeDefinition())
.Contains(typeof(MyInterface<,>));
EDIT: As Jon points out in the comments, you could also do:
bool result1 = type.GetInterfaces()
.Where(i => i.IsGenericType)
.Any(i => i.GetGenericTypeDefinition() == typeof(MyInterface<,>));
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<>))
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() )
....
How can I check if a generic type implements an interface
You can use Type.IsAssignableTo(Type)
typeof( T ).IsAssignableTo( typeof( IIdentifiableEntity<long> ) )
Determine if a class implements a generic interface and then call a the interfaces method
I am almost sure that the approach you are following isn't the most fit for the high level problem you are trying to solve, so I'd be very glad if you could explain exactly what that problem is, so I can give ou better advices.
Said that, the response to the question you are asking is:
I want to have a generic method in my Data Repository that can determine
if a class implements TListDto. If it does, it converts the a list from
List to List by calling the objects TListDto() implementation
try {
var iList = list.Cast<IListDto<TListDto>>();
return iList.Select(s => s.ToListDto()).ToList();
} catch (InvalidCastException) {
throw new ApplicationException("Entity does not implement IListDto");
}
Get type that implements generic interface by searching for a specific generic interface parameter
To refactor @lucky's answer, I prefer comparing the types with the generic type definition instead of using the type name:
static readonly Type GenericIEnumerableType = typeof(IEnumerable<>);
//Find all types that implement IEnumerable<T>
static IEnumerable<T> FindAllEnumerableTypes<T>(Assembly assembly) =>
assembly
.GetTypes()
.Where(type =>
type
.GetInterfaces()
.Any(interf =>
interf.IsGenericType
&& interf.GetGenericTypeDefinition() == GenericIEnumerableType
&& interf.GenericTypeArguments.Single() == typeof(T)));
Alternatively, you can check if interf
is assignable from GenericIEnumerableType.MakeGenericType(typeof(T))
or the other way around.
Related Topics
Taskscheduler.Unobservedtaskexception Event Handler Never Being Triggered
Aes Encryption in Java and Decryption in C#
Maxlength Attribute Not Generating Client-Side Validation Attributes
How to Allow an Anonymous User Access to Some Given Page in MVC
Check If a String Is a Palindrome
Method Overloading. Can You Overuse It
Irregular Shaped Windows Form (C#)
How to Call a .Net Assembly from C/C++
Instantiating a Python Class in C#
How to Delete Cookies on an ASP.NET Website
How to Create a Progress Bar with Rounded Corners in iOS Using Xamarin.Forms
Xamarin: How to Get HTML from Page in Webview
Feasibility of C# Development with Mono
Signalr Owin Self-Host on Linux/Mono Socketexception When Clients Lose Connection
Is There a Tool for Finding Unreferenced Functions (Dead, Obsolete Code) in a C# App