Matias Cicero
Matias Cicero

Reputation: 26281

Using typeof as a generic type argument

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)>();

Upvotes: 7

Views: 1527

Answers (1)

maraaaaaaaa
maraaaaaaaa

Reputation: 8163

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>();

Upvotes: 3

Related Questions