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?
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.
GetType(String) Gets the Type with the specified name, performing a case-sensitive search.
Not really. You need to use reflection, basically. Generics are really aimed at static typing rather than types only known at execution time.
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.
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());
No, it doesn't, because the "generic-type-string" is part of the name of type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With