In C#, the following type-inference works:
var s = "abcd";
But why can’t the type be inferred when the variable is a constant?
The following throws a compile-time exception:
const var s = "abcd"; // <= Compile time error:
// Implicitly-typed local variables cannot be constant
If there’s something you want brought to my attention, you can leave my name in the text — not a comment — and I’ll find it eventually. Or, better, you can “tweet” to
@ericlippert. Note that this does not constitute a service level agreement; I do this in my spare time.“constant” and “variable” are opposites.
const vargives me the shudders to type. A constant is a value that never changes and has no storage location; a variable is a storage location whose contents change. They’re completely different, so don’t attempt to combine them. Thevarsyntax was chosen to call out “this is a variable”, and we’re sticking with it.varcan stand in for a specific type declaration, but combining it withconstseverely muddies the picture of what the compiler does with the value. Thereforeconst varis disallowed to prevent this confusion and you have to explicitly type your constants.I would be perfectly fine with inferred constants that do not use
var:seems fine to me. However, I know of no plans to add this to C#.