Darin's answer is correct, but it's also worth noting that if you receive an instance of T
as a parameter you can use .GetType()
as well:
public void Test<T>(T target)
{
Console.WriteLine("The supplied type is {0}", target.GetType());
}
Just a different approach (typeof
will inspect the type argument whereas .GetType()
works with an instance of the type).
As Daniel notes in the comments there is a nuance to consider: typeof(T)
will return the type-argument's Type, whereas .GetType()
will return the exact type of the object--which may inherit from T
, and typeof(T).IsAssignableFrom(target.GetType())
may return true--but the specific concrete types may differ.
An example:
using System;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
GenericClass<TypeX>.GenericMethod(new TypeX());
GenericClass<TypeX>.GenericMethod(new TypeY());
Console.ReadKey();
}
}
public class TypeX {}
public class TypeY : TypeX {}
public static class GenericClass<T>
{
public static void GenericMethod(T target)
{
Console.WriteLine("TypeOf T: " + typeof(T).FullName);
Console.WriteLine("Target Type: " + target.GetType().FullName);
Console.WriteLine("T IsAssignable From Target Type: " + typeof(T).IsAssignableFrom(target.GetType()));
}
}
}
Resulting output:
Passing in an instance of TypeX as the parameter:
TypeOf T: ConsoleApplication2.TypeX
Target Type: ConsoleApplication2.TypeX
T IsAssignable From Target Type: True
Passing in an instance of TypeY as the parameter:
TypeOf T: ConsoleApplication2.TypeX
Target Type: ConsoleApplication2.TypeY
T IsAssignable From Target Type: True