Skip to content

Commit

Permalink
feat: Added TypeHelper.GetNiceNameOfGenericType() method
Browse files Browse the repository at this point in the history
  • Loading branch information
SolidAlloy committed Feb 12, 2022
1 parent 51b175a commit 2052bcd
Showing 1 changed file with 57 additions and 0 deletions.
57 changes: 57 additions & 0 deletions Runtime/Helpers/TypeHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
{
using System;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;

/// <summary>Different helper functions for <see cref="System.Type"/></summary>
Expand Down Expand Up @@ -96,5 +97,61 @@ public static string ReplaceWithBuiltInName(this string fullTypeName, bool withF
return fullTypeName;
}
}

public static string GetNiceNameOfGenericType(Type genericType, bool fullName = false)
{
return genericType.IsGenericTypeDefinition
? GetNiceNameOfGenericTypeDefinition(genericType, fullName)
: GetNiceNameOfGenericTypeWithArgs(genericType, fullName);
}

public static string[] GetNiceArgsOfGenericType(Type genericType)
{
return genericType.IsGenericTypeDefinition
? GetNiceArgsOfGenericTypeDefinition(genericType)
: GetNiceArgsOfGenericTypeWithArgs(genericType);
}

/// <summary>
/// Gets a type name for nice representation of the type. It looks like this: ClassName&lt;T1,T2>.
/// </summary>
private static string GetNiceNameOfGenericTypeDefinition(Type genericTypeWithoutArgs, bool fullName)
{
string typeNameWithoutBrackets = fullName
? genericTypeWithoutArgs.FullName.StripGenericSuffix()
: genericTypeWithoutArgs.Name.StripGenericSuffix();

var argumentNames = GetNiceArgsOfGenericTypeDefinition(genericTypeWithoutArgs);
return $"{typeNameWithoutBrackets}<{string.Join(",", argumentNames)}>";
}

/// <summary>
/// Gets a type name for nice representation of the type. It looks like this: ClassName&lt;int,TestArg>.
/// </summary>
private static string GetNiceNameOfGenericTypeWithArgs(Type genericTypeWithArgs, bool fullName)
{
string typeNameWithoutSuffix = fullName
? genericTypeWithArgs.FullName.StripGenericSuffix()
: genericTypeWithArgs.Name.StripGenericSuffix();

var argumentNames = GetNiceArgsOfGenericTypeWithArgs(genericTypeWithArgs);

return $"{typeNameWithoutSuffix}<{string.Join(",", argumentNames)}>";
}

private static string[] GetNiceArgsOfGenericTypeDefinition(Type genericTypeWithoutArgs)
{
Type[] genericArgs = genericTypeWithoutArgs.GetGenericArguments();
return genericArgs.Select(argument => argument.Name).ToArray();
}

private static string[] GetNiceArgsOfGenericTypeWithArgs(Type genericTypeWithArgs)
{
return genericTypeWithArgs.GetGenericArguments()
.Select(argument => argument.FullName)
.Select(argFullName => argFullName.ReplaceWithBuiltInName())
.Select(argFullName => argFullName.GetSubstringAfterLast('.'))
.ToArray();
}
}
}

0 comments on commit 2052bcd

Please sign in to comment.