Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)>();
like image 780
Matias Cicero Avatar asked Jun 12 '15 18:06

Matias Cicero


1 Answers

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>();
like image 145
maksymiuk Avatar answered Sep 29 '22 16:09

maksymiuk