Skip to content

Instantly share code, notes, and snippets.

@flakey-bit
Created February 6, 2020 20:43
Show Gist options
  • Save flakey-bit/d444b28ef6e1fd627b5a64452e7bcc76 to your computer and use it in GitHub Desktop.
Save flakey-bit/d444b28ef6e1fd627b5a64452e7bcc76 to your computer and use it in GitHub Desktop.
Useful extensions for Types in C#
// Explodes a type (i.e. recursively gets all generic type parameters)
public static class TypeExtensions
{
public static ISet<Type> Explode(this Type t)
{
return ExplodeType(t);
}
private static ISet<Type> ExplodeType(Type t, ISet<Type> result = null)
{
if (result == null)
{
result = new HashSet<Type>();
}
if (t == null)
{
return result;
}
// Only continue processing if we haven't seen this type before to avoid cycles
if (result.Add(t))
{
if (t.IsGenericTypeDefinition)
{
throw new ArgumentException(nameof(t));
}
if (t.IsGenericType)
{
foreach (var typeArg in t.GenericTypeArguments)
{
ExplodeType(typeArg, result);
}
}
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment