George Polevoy George Polevoy -3 years ago 156
C# Question

Given a type instance, how to get generic type name in C#?

Given a generic type, including


how do i get a generic name for C#?

var t = typeof(Nullable<DateTime>);
var s = t.GetGenericTypeDefinition().Name + "<" + t.GetGenericArguments()[0].Name + ">";

This yields


, but i need



Answer Source

I see you already accepted an answer, but honestly, that answer isn't going to be enough to do this reliably if you just combine what's in there with what you already wrote. It's on the right track, but your code will only work for generic types with exactly one generic parameter, and it will only work when the generic type parameter itself is not generic!

This is a function (written as an extension method) that should actually work in all cases:

public static class TypeExtensions
    public static string ToGenericTypeString(this Type t)
        if (!t.IsGenericType)
            return t.Name;
        string genericTypeName = t.GetGenericTypeDefinition().Name;
        genericTypeName = genericTypeName.Substring(0,
        string genericArgs = string.Join(",",
                .Select(ta => ToGenericTypeString(ta)).ToArray());
        return genericTypeName + "<" + genericArgs + ">";

This function is recursive and safe. If you run it on this input:

    typeof(Dictionary<string, List<Func<string, bool>>>)

You get this (correct) output:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download