Last active
March 6, 2023 09:24
-
-
Save MiloszKrajewski/9f1e29e70a6b35768fa7b50d5bf0f69c to your computer and use it in GitHub Desktop.
This file contains 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
using System; | |
using System.Collections.Concurrent; | |
using System.Linq; | |
using System.Runtime.CompilerServices; | |
using System.Text; | |
namespace K4os.Fx; | |
internal static class ReflectionExtensions | |
{ | |
private static readonly ConcurrentDictionary<Type, string> FriendlyNamesCache = new(); | |
public static string GetFriendlyName(this Type? type) => | |
type is null ? "<null>" : FriendlyNamesCache.GetOrAdd(type, BuildFriendlyName); | |
private static string BuildFriendlyName(Type? type) | |
{ | |
if (type is null) return "<null>"; | |
var typeName = type.Name; | |
if (!type.IsGenericType) | |
return typeName; | |
var length = typeName.IndexOf('`'); | |
if (length < 0) length = typeName.Length; | |
return new StringBuilder() | |
.Append(typeName, 0, length) | |
.Append('<') | |
.Append(string.Join(",", type.GetGenericArguments().Select(GetFriendlyName))) | |
.Append('>') | |
.ToString(); | |
} | |
public static string GetObjectFriendlyName(this object? subject) => | |
subject is null | |
? "<null>" | |
: $"{subject.GetType().GetFriendlyName()}@{RuntimeHelpers.GetHashCode(subject):x}"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment