George Polevoy George Polevoy - 1 year ago 93
C# Question

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

Given a generic type, including

List<string>
Nullable<Int32>


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

"Nullable`1<DateTime>"


, but i need

"Nullable<DateTime>"


.

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,
            genericTypeName.IndexOf('`'));
        string genericArgs = string.Join(",",
            t.GetGenericArguments()
                .Select(ta => ToGenericTypeString(ta)).ToArray());
        return genericTypeName + "<" + genericArgs + ">";
    }
}

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

Console.WriteLine(
    typeof(Dictionary<string, List<Func<string, bool>>>)
    .ToGenericTypeString());

You get this (correct) output:

Dictionary<String,List<Func<String,Boolean>>>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download