Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get type name without full namespace

I have the following code:

return "[Inserted new " + typeof(T).ToString() + "]";

But

 typeof(T).ToString()

returns the full name including namespace

Is there anyway to just get the class name (without any namespace qualifiers?)

like image 244
leora Avatar asked Aug 03 '10 12:08

leora


3 Answers

typeof(T).Name // class name, no namespace
typeof(T).FullName // namespace and class name
typeof(T).Namespace // namespace, no class name
like image 133
Tim Robinson Avatar answered Nov 08 '22 03:11

Tim Robinson


Try this to get type parameters for generic types:

public static string CSharpName(this Type type)
{
    var sb = new StringBuilder();
    var name = type.Name;
    if (!type.IsGenericType) return name;
    sb.Append(name.Substring(0, name.IndexOf('`')));
    sb.Append("<");
    sb.Append(string.Join(", ", type.GetGenericArguments()
                                    .Select(t => t.CSharpName())));
    sb.Append(">");
    return sb.ToString();
}

Maybe not the best solution (due to the recursion), but it works. Outputs look like:

Dictionary<String, Object>
like image 41
gregsdennis Avatar answered Nov 08 '22 03:11

gregsdennis


make use of (Type Properties)

 Name   Gets the name of the current member. (Inherited from MemberInfo.)
 Example : typeof(T).Name;
like image 11
Pranay Rana Avatar answered Nov 08 '22 05:11

Pranay Rana