Skip to content

Instantly share code, notes, and snippets.

@Quahu
Last active February 12, 2020 01:05
Show Gist options
  • Save Quahu/50b1468414ebeee58e439bfab0299e84 to your computer and use it in GitHub Desktop.
Save Quahu/50b1468414ebeee58e439bfab0299e84 to your computer and use it in GitHub Desktop.
Humanize C# generic types.
public static string Humanize(this Type type, bool includeNamespace = false)
{
// simply return its name
if (!type.IsGenericType)
return includeNamespace ? $"{type.Namespace}.{type.Name}" : type.Name;
// what are you doing
if (type.IsNested && type.DeclaringType.IsGenericType)
throw new NotImplementedException();
// generics, but done correctly
// MyType<TypeOne, TypeTwo>
return $"{(includeNamespace ? $"{type.Namespace}." : "")}{type.Name.Substring(0, type.Name.IndexOf('`'))}<{string.Join(", ", type.GetGenericArguments().Select(x => x.Humanize(includeNamespace)))}>";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment