Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get name of generic class without tilde [duplicate]

I am trying to get the type name of T using this:

typeof(T).Name

The name of the class is ConfigSettings

Instead of returning ConfigSettings it is returning ConfigSettings`1.

Is there any specific reason why? How can I return the actual name without `1?

like image 674
user2483744 Avatar asked Jul 05 '13 04:07

user2483744


People also ask

Is it possible to inherit from a generic type?

An attribute cannot inherit from a generic class, nor can a generic class inherit from an attribute.

How do you call a generic using reflection?

The first step to dynamically invoking a generic method with reflection is to use reflection to get access to the MethodInfo of the generic method. To do that simply do this: var methodInfo = typeof(ClassWithGenericMethod). GetMethod("MethodName");

Can you create instances of generic type parameters?

A generic type is like a template. You cannot create instances of it unless you specify real types for its generic type parameters. To do this at run time, using reflection, requires the MakeGenericType method.

Can you have a generic method in a non-generic class?

Generic methods in non-generic classYes, you can define a generic method in a non-generic class in Java.


1 Answers

Here is an extension method that will get the "real" name of a generic type along with the names of the generic type parameters. It will properly handle nested generic types.

public static class MyExtensionMethods
{
    public static string GetRealTypeName(this Type t)
    {
        if (!t.IsGenericType)
            return t.Name;

        StringBuilder sb = new StringBuilder();
        sb.Append(t.Name.Substring(0, t.Name.IndexOf('`')));
        sb.Append('<');
        bool appendComma = false;
        foreach (Type arg in t.GetGenericArguments())
        {
            if (appendComma) sb.Append(',');
            sb.Append(GetRealTypeName(arg));
            appendComma = true;
        }
        sb.Append('>');
        return sb.ToString();
    }
}

Here is a sample program showing its usage:

static void Main(string[] args)
{
    Console.WriteLine(typeof(int).GetRealTypeName());
    Console.WriteLine(typeof(List<string>).GetRealTypeName());
    Console.WriteLine(typeof(long?).GetRealTypeName());
    Console.WriteLine(typeof(Dictionary<int, List<string>>).GetRealTypeName());
    Console.WriteLine(typeof(Func<List<Dictionary<string, object>>, bool>).GetRealTypeName());
}

And here is the output of the above program:

Int32
List<String>
Nullable<Int64>
Dictionary<Int32,List<String>>
Func<List<Dictionary<String,Object>>,Boolean>
like image 57
Brian Rogers Avatar answered Sep 28 '22 09:09

Brian Rogers