Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
using System;
using System.Collections.Generic;
using System.Linq;
namespace [YOURNAMESPACEHERE]
{
public static class TypeExtensions
{
public static bool IsDerivingFrom(this Type type, Type searchType)
{
if (type == null) throw new NullReferenceException();
return
type.BaseType != null &&
(type.BaseType == searchType ||
type.BaseType.IsDerivingFrom(searchType));
}
public static bool IsDerivingFromGenericType(this Type type, Type searchGenericType)
{
if (type == null) throw new ArgumentNullException(nameof(type));
if (searchGenericType == null) throw new ArgumentNullException(nameof(searchGenericType));
return
type != typeof(object) &&
(type.IsGenericType &&
searchGenericType.GetGenericTypeDefinition() == searchGenericType ||
IsDerivingFromGenericType(type.BaseType, searchGenericType));
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Extension method")]
public static Type GetItemType<T>(this IEnumerable<T> enumerable) => typeof(T);
public static Type? GetItemType(this object enumerable)
=> enumerable == null ? null :
(enumerable.GetType().GetInterface(typeof(IEnumerable<>).Name)?.GetGenericArguments()[0]);
public static bool ImplementsInterface(this Type? type, Type? @interface)
{
bool result = false;
if (type == null || @interface == null)
return result;
var interfaces = type.GetInterfaces();
if (@interface.IsGenericTypeDefinition)
{
foreach (var item in interfaces)
{
if (item.IsConstructedGenericType && item.GetGenericTypeDefinition() == @interface)
result = true;
}
}
else
{
foreach (var item in interfaces)
{
if (item == @interface)
result = true;
}
}
return result;
}
public static Type? FindType(this string name)
{
Type? result = null;
var nonDynamicAssemblies = AppDomain.CurrentDomain.GetAssemblies().Where(a => !a.IsDynamic);
try
{
result = nonDynamicAssemblies.
SelectMany(a => a.GetExportedTypes()).
FirstOrDefault(t => t.Name == name);
}
catch
{
result = nonDynamicAssemblies.
SelectMany(a => a.GetTypes()).
FirstOrDefault(t => t.Name == name);
}
return result;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment