Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A neater GetType().ToString() for closed generics

Tags:

c#

I can't believe that this hasn't been asked before but as I am unable to find this particular "needle" in the stackoverflow haystack I'm asking it.

I would like a neater implementation of GetType().ToString() for closed generic types. By neater I mean that I would like the ToString() call to return a string in the format I would have typed into the development environment.

The default GetType().ToString() on a closed generic will place `n where n is the number of types, and uses [ ]'s instead of <>'s.

Anyway ... to the code.

given the following classes:

A a = new A();
C<A> c = new C<A>();
D<A, B> d = new D<A, B>();
E<B, C<A>, D<A, B>> e = new E<B, C<A>, D<A, B>>();

The default .ToString() returns:

AAA.Events.A
AAA.Events.C`1[AAA.Events.A]
AAA.Events.D`2[AAA.Events.A,AAA.Events.B]
AAA.Events.E`3[AAA.Events.B,AAA.Events.C`1[AAA.Events.A],AAA.Events.D`2

I've written some basic old school (pre linq) code to produce:

AAA.Events.A
AAA.Events.C<AAA.Events.A>
AAA.Events.D<AAA.Events.A,AAA.Events.B>
AAA.Events.E<AAA.Events.B,AAA.Events.C<AAA.Events.A>,AAA.Events.D<AAA.Events.A,AAA.Events.B>>

But I would really like it to return:

A
C<A>
D<A,B>
E<B,C<A>,D<A,B>>

Here's the shoddy code I have written to demonstrate my intent:

public static string NeaterString(this Type t)
{
    string neater = t.ToString();
    if (neater.Contains('`'))
    {
        while (neater.Contains('`'))
        {
            neater = neater.Remove(neater.IndexOf('`'), 2);
        }
        return neater.Replace('[', '<').Replace(']', '>');
    }
    else return neater; 
}
like image 378
qujck Avatar asked Dec 16 '22 15:12

qujck


1 Answers

I would try to avoid as much string parsing as possible. My routine looks like this:

public static string GetFriendlyName(Type type)
{
    if (type.IsGenericType)
        return string.Format("{0}<{1}>", type.Name.Split('`')[0], string.Join(", ", type.GetGenericArguments().Select(x => GetFriendlyName(x))));
    else
        return type.Name;
}
like image 50
Kirk Woll Avatar answered Dec 31 '22 00:12

Kirk Woll