Get type name without full namespace
Asked Answered
T

6

370

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

Talbot answered 3/8, 2010 at 12:12 Comment(4)
Incidentally, writing string1 + anything.ToString() + string2 is redundant. The compiler inserts the call to ToString automatically if you do string1 + anything + string2.Tanjatanjore
not to sound harsh but, had you inspected what properties are available on the Type instance (as returned by typeof(..)) I'm pretty sure you'd figure out this yourself...Poore
For some reason the Name property is missing from the documentation - at least, it's not where I was looking for it.Tabina
@MichaelKay Name is member of MemberInfo which is base class of Type.Dropline
T
669
typeof(T).Name // class name, no namespace
typeof(T).FullName // namespace and class name
typeof(T).Namespace // namespace, no class name
Tanjatanjore answered 3/8, 2010 at 12:13 Comment(3)
Name doesn't consider type parameters.Venita
Or this.GetType().Name, this.GetType().FullName, etc. if dealing with instances.Animadversion
Name also doesn't consider nested types!Simonasimonds
V
42

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>
Venita answered 29/6, 2013 at 3:43 Comment(5)
This ought to be the accepted answer as it properly takes into consideration generic types which may recurse (Dictionary<int?,int?> for instance).Became
+1 for the concept. But dislike the failed premature optimisation. It creates a new StringBuilder in each recursive call (even the base case when it's unused), yet ignores the string.Join temporary and LINQ lambda. Just use String until you know it's a bottleneck. /rantBohemian
Nigel, it says right there that's is probably not the best solution :)Venita
ShortName is a shorter name :)Beefsteak
While the update is appreciated, this was answered almost a decade ago. I've used updated versions in my own code since. (Maybe I should have updated here.)Venita
L
12

make use of (Type Properties)

 Name   Gets the name of the current member. (Inherited from MemberInfo.)
 Example : typeof(T).Name;
Limerick answered 3/8, 2010 at 12:15 Comment(0)
S
10

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

Sister answered 7/4, 2017 at 13:27 Comment(3)
nameof does not return the name of the TypeBohemian
@NigelTouch I've checked and nameof return the name of the Type, screenshot with proof: prntscr.com/irfk2cSister
Sorry, I didn't explain well. What I mean is that it does 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<string>". It don't think it answers the OP's question.Bohemian
A
9
you can do this:
typeof(T).Name;
Amethist answered 3/8, 2010 at 12:20 Comment(0)
C
2

You can use the Type.Name property to get just the class name without the namespace qualifiers.

return "[Inserted new " + typeof(T).Name + "]";
Carping answered 24/11, 2023 at 15:11 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.