Using typeof as a generic type argument

1.5k views Asked by At

According to the documentation of typeof:

[...] To obtain the run-time type of an expression, you can use the .NET Framework method GetType

Therefore, this means that typeof must be a compile-time expression.

In the article about Generic Type Parameters, it is stated that:

[...] The type argument for this particular class can be any type recognized by the compiler.

Any type recognized by the compiler is any type inferred by the compiler, i.e. any type that is known at compile time.

If this is true, then why does the following statement is not allowed?

int value = GenericMethod<typeof(int)>();
1

There are 1 answers

0
maraaaaaaaa On

typeof() returns a Type object, just like .GetType() would, it cannot be used in place of a type. What you could do though is put <T> after your class name, then:

T value = GenericMethod<T>();