Search code examples
c#compiler-optimizationcompile-time-constantgeneric-type-argument

Will this comparison be compiled into a constant Boolean value in a generic class?


Will typeof(T) == typeof(string) where T is a generic type argument, be compiled into a constant Boolean value, since the condition is knowable at compile time?


Solution

  • Generic type data exists in the IL - it is not erased like in Java. So: no, the C# compiler doesn't compile this to a constant; it compiles it the IL that talks about a generic type parameter.

    The JIT on this is then reused for all reference type permutations (only each value-type permutation requires a separate JIT, for size/boxing/etc reasons). Since string is a reference-type, this means that Foo<string> (where typeof(T)==typeof(string) is true) uses the same JIT output as Foo<SomeClass> (where typeof(T)==typeof(string) is false). So no: this is explicitly not a constant, even at JIT time.