Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get type name without any generics info

Tags:

If I write:

var type = typeof(List<string>); Console.WriteLine(type.Name); 

It will write:

List`1

I want it to write just:

List

How can I do that? Is there a smarter way to do it without having to use Substring or similar string manipulation functions?

like image 866
Allrameest Avatar asked Jun 17 '11 13:06

Allrameest


People also ask

How do you find the type of generic type?

Use the IsGenericType property to determine whether the type is generic, and use the IsGenericTypeDefinition property to determine whether the type is a generic type definition. Get an array that contains the generic type arguments, using the GetGenericArguments method.

What is GetType () name in C#?

GetType(String) Gets the Type with the specified name, performing a case-sensitive search.

Can dynamic type be used for generic?

Not really. You need to use reflection, basically. Generics are really aimed at static typing rather than types only known at execution time.

Can struct be generic?

In addition to generic classes, you can also create a generic struct. Like a class, the generic struct definition serves as a sort of template for a strongly-typed struct. When you declare a variable of this struct type, you provide a type for its generic parameter.


2 Answers

No, it makes perfect sense for it to include the generic arity in the name - because it's part of what makes the name unique (along with assembly and namespace, of course).

Put it this way: System.Nullable and System.Nullable<T> are very different types. It's not expected that you'd want to confuse the two... so if you want to lose information, you're going to have to work to do it. It's not very hard, of course, and can be put in a helper method:

public static string GetNameWithoutGenericArity(this Type t) {     string name = t.Name;     int index = name.IndexOf('`');     return index == -1 ? name : name.Substring(0, index); } 

Then:

var type = typeof(List<string>); Console.WriteLine(type.GetNameWithoutGenericArity()); 
like image 52
Jon Skeet Avatar answered Oct 25 '22 16:10

Jon Skeet


No, it doesn't, because the "generic-type-string" is part of the name of type.

like image 27
TcKs Avatar answered Oct 25 '22 14:10

TcKs