Created
February 6, 2020 20:43
-
-
Save flakey-bit/d444b28ef6e1fd627b5a64452e7bcc76 to your computer and use it in GitHub Desktop.
Useful extensions for Types in C#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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