Search code examples
c#compiler-errorsswitch-statementtostringtypeof

Why typeof(int).ToString() is not constant?


I'm trying to do this:

const string intType = typeof(int).ToString();
switch (typeof(MyT).ToString())
{
    case intType:
    {
        return "int";
        break;
    }
    ...
}

But compiler says:

error CS0133: The expression being assigned to 'intType' must be constant

As I know, typeof operator works at compile-time. So, what's wrong?


Solution

  • As I know, typeof operator works at compile-time.

    You don't know that because knowledge has to be true. Where did you get the idea that typeof is executed at compile time? It produces a non-constant object. And then there is no guarantee that ToString doesn't produce a different string every time it runs, so it cannot be treated as a constant either.

    So, what's wrong?

    You're reasoning from a false belief.

    The C# specification clearly describes the conditions that must be met for an expression to be a compile-time constant. Those conditions include the expression not containing any typeof operator or method call.

    But there are far bigger problems here. I assume that MyT is a generic type parameter, which means you are attempting to switch on the value of a generic type parameter. That is almost always the wrong thing to do.

    What are you really trying to do? What problem are you really trying to solve? Because this code you've shown so far indicates that you're going down an unproductive path to solve whatever the real problem is.