0

Here is signature of the function:

public static T[] Shuffle<T>(T[] array)

Inside the function I want to check the type:

var t = T.GetType();

But I get this error:

'T' is a type parameter, which is not valid in the given context

Any idea why I get error and how to get type of T?

Michael
  • 13,950
  • 57
  • 145
  • 288
  • https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/typeof – Waayd Jul 28 '18 at 14:39
  • GetType() is only valid on an object. T is not an object, it is a type. Simply use typeof(T). Do beware it is a smell, code that needs it is rarely generic code. – Hans Passant Jul 28 '18 at 15:01

2 Answers2

3

You can use typeof to get the type of a generic parameter: typeof(T)

Selman Genç
  • 100,147
  • 13
  • 119
  • 184
2

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.

Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188