From 5067f5fdb397c5c25b5c7adaaa310f54bb8d09e9 Mon Sep 17 00:00:00 2001 From: Chris Cameron Date: Mon, 6 Apr 2020 13:11:05 -0400 Subject: [PATCH] feat: Added Type extension method for getting inner generic types --- ICD.Common.Utils/Extensions/TypeExtensions.cs | 28 ++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/ICD.Common.Utils/Extensions/TypeExtensions.cs b/ICD.Common.Utils/Extensions/TypeExtensions.cs index 9810b26..4e7060b 100644 --- a/ICD.Common.Utils/Extensions/TypeExtensions.cs +++ b/ICD.Common.Utils/Extensions/TypeExtensions.cs @@ -208,13 +208,39 @@ namespace ICD.Common.Utils.Extensions return to.IsAssignableFrom(from); } + /// + /// Extracts the inner Types from this current Type inheriting/implementing the given generic Type. + /// E.g. + /// typeof(List<int>).GetInnerGenericTypes(typeof(IEnumerable<>)); + /// Returns + /// [ typeof(int) ] + /// + /// + /// + /// + [NotNull] + public static IEnumerable GetInnerGenericTypes([NotNull] this Type extends, Type genericType) + { + if (extends == null) + throw new ArgumentNullException("extends"); + + if (genericType == null) + throw new ArgumentNullException("genericType"); + + return extends + .GetAllTypes() + .First(t => t.IsGenericType && + t.GetGenericTypeDefinition() == genericType) + .GetGenericArguments(); + } + /// /// Returns the given type, all base types, and all implemented interfaces. /// /// /// [NotNull] - public static IEnumerable GetAllTypes([NotNull]this Type extends) + public static IEnumerable GetAllTypes([NotNull] this Type extends) { if (extends == null) throw new ArgumentNullException("extends");