7

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)>();
Matias Cicero
  • 25,439
  • 13
  • 82
  • 154
  • 5
    Because `typeof()` returns you a `Type` object that represents the argument. It is not a type itself. It's also an expression, which is not allowed in that spot according to the C#LS. – Jeroen Vannevel Jun 12 '15 at 18:15

1 Answers1

3

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>();
maraaaaaaaa
  • 7,749
  • 2
  • 22
  • 37