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?
First of all
typeofis actually turned by compiler into method call:is represented in IL with:
@sharplab.io
As for treating some expressions involving
typeofas "constant ones" there are several suggestions already:System.Type(basically what you want)