views:

170

answers:

2

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>"

.

+1  A: 

if you really need "Nullable<DateTime>" just do:

string name = t.GetGenericTypeDefinition().Name;
name = name.Substring(0,name.IndexOf('`'));
Andrey
That would just get you the word "Nullable." He wants the whole name as it would be written in C#.
Aaronaught
i think author understood me :) i told how to convert Nullable`1 to Nullable, second part he did without me
Andrey
+6  A: 

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>>>
Aaronaught
It's a pity the CLR does not come with this function.
Paul Ruane
@Paul Ruane: I agree that it could be useful in certain cases, however, the CLR is language-agnostic, and there'd be no way to implement something like this so as to work equally well in C#, VB.NET, F#, IronPython, and all of the other CLR languages. The weird-looking name with the backtick is actually the true CLR type name; the format above is C# specific.
Aaronaught
@Aaronaught: Ah yes, good point. I have tunnel C# vision!
Paul Ruane
There could be at least an helper function in the Microsoft.CSharp namespace. That namespace contains language-specific classes.
BladeWise