Skip to content

Instantly share code, notes, and snippets.

@werwolfby
Created March 20, 2020 06:41
Show Gist options
  • Save werwolfby/237fb8c5c38fe2877250af85e94e9cd8 to your computer and use it in GitHub Desktop.
Save werwolfby/237fb8c5c38fe2877250af85e94e9cd8 to your computer and use it in GitHub Desktop.
Search type (base or interface) in type with ability to search concrete type by generic type definition
using System;
namespace DataAccess
{
public static class TypeExtensions
{
public static Type? SearchType(this Type type, Type searchType)
{
return searchType.IsInterface
? SearchInterfaceType(type, searchType)
: SearchBaseType(type, searchType);
static Type? SearchInterfaceType(Type type, Type searchType)
{
foreach (var interfaceType in type.GetInterfaces())
{
var searchedType = CompareType(interfaceType, searchType);
if (searchedType != null)
{
return searchType;
}
}
return null;
}
static Type? SearchBaseType(Type type, Type searchType)
{
Type? currentType = type;
while (currentType != null)
{
var searchedType = CompareType(currentType, searchType);
if (searchedType != null)
{
return searchType;
}
currentType = currentType.BaseType;
}
return null;
}
static Type? CompareType(Type type, Type searchType)
{
var compareType = type;
if (searchType.IsGenericTypeDefinition && type.IsGenericType)
{
compareType = type.GetGenericTypeDefinition();
}
return compareType == searchType ? type : null;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment