Search code examples
c#declarationimplicit-declaration

Why can't I declare a constant using var in C#?


this:

const int a = 5;

compiles just fine, whereas

const var a = 5;

doesn't... while:

var a = 5;

compiles just as well as this:

int a = 5;

why?


Solution

  • The var keyword was intended to save you from writing long complex typenames, which cannot be constants.

    It is very convenient to be able to write declarations like

    var dict = new Dictionary<string, List<Definition>>();
    

    It becomes necessary when using anonymous types.

    For constants, this isn't an issue.
    The longest built-in typename with constant literals is decimal; that's not a very long name.

    It is possible to have arbitrarily long enum names which can be used as constants, but the C# compiler team apparently wasn't concerned for that.
    For one thing, if you're making a constant enum value, you might as well put it in the enum.
    Also, enum names shouldn't be too long. (Unlike complex generic types, which can and frequently should)