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)>();
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>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With