Type-inferring a constant in C#

后端 未结 11 1173
花落未央
花落未央 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:32

    In this case it is obvious that you know the reference type will be constant, and of a fairly primitive type (consts can only be value types, or strings, etc..), so you should declare that type, rather than use implicit typing.

    In other words, because the type is obviously constant and known, there's absolutely no reason to use var.

    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.

    http://msdn.microsoft.com/en-us/library/bb310881.aspx

    Compiler Error CS0822

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

提交回复
热议问题