Skip to content

Instantly share code, notes, and snippets.

@bronumski
Created November 3, 2023 16:13
Show Gist options
  • Save bronumski/f3639f0c861642e58507e1c10df78f2d to your computer and use it in GitHub Desktop.
Save bronumski/f3639f0c861642e58507e1c10df78f2d to your computer and use it in GitHub Desktop.
Type extensions
static class TypeExtensions
{
public static IEnumerable<Type> GetInstanceTypesImplementing<T>(
this Assembly assembly, params Assembly[] assemblies)
{
var serviceType = typeof(T);
return assemblies.Union(new [] { assembly }).SelectMany(x => x.GetTypes())
.Where( x => x.IsClass && !x.IsAbstract && serviceType.IsAssignableFrom( x ) );
}
public static IEnumerable<Type> GetTypesDecoratedWith<T>(
this Assembly assembly, params Assembly[] assemblies ) where T : Attribute
{
var decoratorType = typeof(T);
return assemblies.Union(new [] { assembly }).SelectMany(x => x.GetTypes())
.Where( x => x.IsClass && !x.IsAbstract && x.GetCustomAttributes(decoratorType, true ).Any());
}
public static bool ImplementsGenericInterface(
this Type typeToInspect, Type genericInterface)
=> genericInterface.IsGenericTypeDefinition is false
? throw new InvalidOperationException( $"Expected type '{genericInterface}' to be a generic type definition" )
: typeToInspect
.GetInterfaces()
.Any( x => x.IsGenericType && x.GetGenericTypeDefinition() == genericInterface );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment