Problem
The following is the code I have:
return "[Inserted new " + typeof(T).ToString() + "]";
But
typeof(T).ToString()
The whole name, including the namespace, is returned.
Is it possible to get the class name alone (without any namespace qualifiers)?
Asked by leora
Solution #1
typeof(T).Name // class name, no namespace
typeof(T).FullName // namespace and class name
typeof(T).Namespace // namespace, no class name
Answered by Tim Robinson
Solution #2
To acquire type parameters for generic types, do this:
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();
}
It’s not the most elegant solution (due to the recursion), but it gets the job done. The following are examples of outputs:
Dictionary<String, Object>
Answered by gregsdennis
Solution #3
take advantage of (Type Properties)
Name Gets the name of the current member. (Inherited from MemberInfo.)
Example : typeof(T).Name;
Answered by Pranay Rana
Solution #4
You can use nameof expression: after C# 6.0 (included).
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 that nameof does not return the runtime Type of the underlying object; it is only a compile-time input. If a method accepts an IEnumerable, nameof returns “IEnumerable,” even if the real object is “List.”
Answered by Stas Boyarincev
Solution #5
typeof(T).Name;
Answered by Datoon
Post is based on https://stackoverflow.com/questions/3396300/get-type-name-without-full-namespace