This project is read-only.

shorthand for constants

Topics: C# Language Design
Apr 6, 2014 at 5:08 PM
Edited Apr 6, 2014 at 5:09 PM
another inspiration from golang.

current C#
const int i = 0;
const string name = "Prabir";
shorthand alternative
const i = 0;
const name = "Prabir";
This would be very useful for scripting in c# especially due to the popularity of scriptcs.
Apr 7, 2014 at 2:21 AM
Edited Apr 7, 2014 at 2:21 AM
Something similar has been discussed here. I agree that a constant version of var would be very useful. Not sure if you meant at the local or the class level, or both, but I'd like to see it supported in both.

The problem with the suggested syntax is that ambiguity with parsing const int = 0; Should that be valid code? In this case const int int = 0; isn't valid either, but what about const File = 0;. There potentially could be many perfectly valid names which would be disallowed as constant names, and you'd now have to specify a type in order for that expression to compile.

The ambiguity could probably be statically determined in 99% of cases, but I really don't like the fact that adding a using statement could change the parser.

The other thread suggested different syntax that could be supported, right now I'm a fan of using val(for value), so you're examples would be
val i = 0;
val name = "Prabir"
I'm also wondering if the const might be better off as readonly since the compiler is pretty limited in what it considers to be constant, and it may be frustrating having it as a const. The result is pretty similar in either case.

I'm curious to see what everyone else thinks, but I personally think easy syntax for immutable variables would promote much safer code.
Apr 7, 2014 at 7:16 PM
I would definitely love to see both local and class level constants. I actually like val, not sure if that would would be confusing with var when glancing at the code fast. Having val would definitely make creating immutable variables as easy as creating mutable variables. Also I noticed my muscle memory keeps typing varl instead of val.

const could be a for class level while val would could be for local.

const int = 0; shouldn't be valid because int is a reserved keyword. Just as how const int int = 0; isn't a valid code.

const File = 0; should be allowed because const int File = 0; is allowed even when we have System.IO namespace imported.