Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the type name of a generic type argument?

Tags:

c#

generics

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

like image 256
Tomas Aschan Avatar asked Apr 05 '10 22:04

Tomas Aschan


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.

How do you indicate that a class has a generic type parameter?

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.

What is generic type arguments?

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.

What does the T designator indicate in a generic class?

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.


Video Answer


2 Answers

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 
like image 143
Reed Copsey Avatar answered Oct 07 '22 21:10

Reed Copsey


typeof(T).Name and typeof(T).FullName are working for me. I get the type passed as an argument.

like image 28
GR7 Avatar answered Oct 07 '22 21:10

GR7