Could the `typeof` a type literal be considered a compile-time constant?

79 Views Asked by At

I'm aware that currently, one cannot use a typeof() expression and have the compiler consider it compile-time constant in any context.

Unfortunately, that means we miss out on some nice options, for instance being able to switch on the typeof(TGeneric) and use typeof(KnownType) in our cases:

        public MyType MyGenericMethod<T>()
        {
            return typeof(T) switch
                {
                    typeof(KnownTypeA) => return A(),
                    typeof(KnownTypeB) => return B(),
                    typeof(KnownTypeC) => return C()
                };
        }

Now, we can work around that by switching on typeof(T).Name and using nameof(KnownTypeA) in our case. However, I really don't think this should be necessary. So, I'm considering opening a discussion on the csharplang repo.

Before I do this, I wanted to know if there's any situation in which typeof(A.Known.Type) could possibly not be determined at compile time?

1

There are 1 best solutions below

3
Guru Stron On BEST ANSWER

First of all typeof is actually turned by compiler into method call:

Console.WriteLine(typeof(List<object>));

is represented in IL with:

IL_0000: ldtoken class [System.Collections]System.Collections.Generic.List`1<object>
IL_0005: call class [System.Runtime]System.Type [System.Runtime]System.Type::GetTypeFromHandle(valuetype [System.Runtime]System.RuntimeTypeHandle)
IL_000a: call void [System.Console]System.Console::WriteLine(object)

@sharplab.io

As for treating some expressions involving typeof as "constant ones" there are several suggestions already: