If I have a method signature like
public string myMethod<T>( ... )
How can I, inside the method, get the name of the type that was given as type argument? I'd like to do something similar to typeof(T).FullName
, but that actually works...
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.
A generic type is declared by specifying a type parameter in an angle brackets after a type name, e.g. TypeName<T> where T is a type parameter.
The generic argument list is a comma-separated list of type arguments. A type argument is the name of an actual concrete type that replaces a corresponding type parameter in the generic parameter clause of a generic type. The result is a specialized version of that generic type.
Its instances (only one per type exists) are used to represent classes and interfaces, therefore the T in Class<T> refers to the type of the class or interface that the current instance of Class represents.
Your code should work. typeof(T).FullName
is perfectly valid. This is a fully compiling, functioning program:
using System; class Program { public static string MyMethod<T>() { return typeof(T).FullName; } static void Main(string[] args) { Console.WriteLine(MyMethod<int>()); Console.ReadKey(); } }
Running the above prints (as expected):
System.Int32
typeof(T).Name
and typeof(T).FullName
are working for me. I get the type passed as an argument.
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