Type-inferring a constant in C#

后端 未结 11 1169
花落未央
花落未央 2020-12-05 13:14

In C#, the following type-inference works:

var s = \"abcd\";

But why can\'t the type be inferred when the variable is a constant?

T

11条回答
  •  半阙折子戏
    2020-12-05 13:50

    The short answer is because the language designers (Microsoft) say so.

    From MSDN:

    Compiler Error CS0822

    Error Message: Implicitly typed locals cannot be const

    Implicitly typed local variables are only necessary for storing anonymous types. In all other cases they are just a convenience. If the value of the variable never changes, just give it an explicit type. Attempting to use the readonly modifier with an implicitly typed local will generate CS0106.

    To correct this error

    If you require the variable to be constant or readonly, give it an explicit type.

提交回复
热议问题