On type names and generic type parameter names given as a C# identifier you can apply the typeof
operator
Type type = typeof(T);
on objects you can call the GetType
method.
Type arrayType = array.GetType();
Type elementType = arrayType.GetElementType();
Note that typeof
yields the static type known at compile time, where as GetType
yields the dynamic type at runtime.
object obj = new Person();
Type staticType = typeof(object); // ==> System.Object
Type runtimeType = obj.GetType(); // ==> Person
Since typeof(T)
yields an object of type System.Type
, you can test for a type with
typeof(T) == typeof(Person)
or
T is Person
however; these two comparisons are not equivalent. If you have
class Student : Person
{ }
And assuming that T
is of type Student
, then
typeof(T) == typeof(Person) ===> false, because it is typeof(Student)
T is Person ===> true, because every type inheriting Person is a Person
The first comparison yields false
, because we test for equality of the two Type
objects that are different.