Get type name without full namespace

C#NamespacesTypeof

C# Problem Overview


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?)

C# Solutions


Solution 1 - C#

typeof(T).Name // class name, no namespace
typeof(T).FullName // namespace and class name
typeof(T).Namespace // namespace, no class name

Solution 2 - C#

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>

Solution 3 - C#

make use of (Type Properties)

 Name	Gets the name of the current member. (Inherited from MemberInfo.)
 Example : typeof(T).Name;

Solution 4 - C#

After the C# 6.0 (including) you can use nameof expression:

using Stuff = Some.Cool.Functionality  
class C {  
    static int Method1 (string x, int y) {}  
    static int Method1 (string x, string y) {}  
    int Method2 (int z) {}  
    string f<T>() => nameof(T);  
}  
  
var c = new C()  
  
nameof(C) -> "C"  
nameof(C.Method1) -> "Method1"   
nameof(C.Method2) -> "Method2"  
nameof(c.Method1) -> "Method1"   
nameof(c.Method2) -> "Method2"  
nameof(z) -> "z" // inside of Method2 ok, inside Method1 is a compiler error  
nameof(Stuff) = "Stuff"  
nameof(T) -> "T" // works inside of method but not in attributes on the method  
nameof(f) -> “f”  
nameof(f<T>) -> syntax error  
nameof(f<>) -> syntax error  
nameof(Method2()) -> error “This expression does not have a name”  

Note! nameof not get the underlying object's runtime Type, it is just the compile-time argument. If a method accepts an IEnumerable then nameof simply returns "IEnumerable", whereas the actual object could be "List".

Solution 5 - C#

you can do this:

typeof(T).Name;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionleoraView Question on Stackoverflow
Solution 1 - C#Tim RobinsonView Answer on Stackoverflow
Solution 2 - C#gregsdennisView Answer on Stackoverflow
Solution 3 - C#Pranay RanaView Answer on Stackoverflow
Solution 4 - C#Stas BoyarincevView Answer on Stackoverflow
Solution 5 - C#DatoonView Answer on Stackoverflow