Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the type of Generic parameter?

Tags:

c#

generics

How can I get the type of generic parameter?

For example:

void Example<T>()
{
  // Here I want to get the type of T (and how can I get if T is a primitive 
  // kind (int,bool,string) not class)
} 
like image 943
David Horák Avatar asked Dec 04 '22 22:12

David Horák


1 Answers

Type type = typeof(T);

That will get you the type object for type T.

type.IsPrimitive will tell you if it's one of the primitive types, see list here: http://msdn.microsoft.com/en-us/library/system.type.isprimitive.aspx

Also, note that although string is a basic type, which is very integrated with the .NET system, it is not a primitive. System.String is a full-fledged class, not a primitive.

like image 163
David Yaw Avatar answered Dec 15 '22 16:12

David Yaw