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?
Variables can be declared as constants by using the “const” keyword before the datatype of the variable. The constant variables can be initialized once only. The default value of constant variables are zero.
Use of the Constants in CIt can be of any data type- character, floating-point, string and double, integer, etc. There are various types of constants in C. It has two major categories- primary and secondary constants. Character constants, real constants, and integer constants, etc., are types of primary constants.
The disadvantage of #define is that is replaces every occurence of the name, while const variables get normal lookup, so you have less risk of naming conflicts and it's not typesafe. The advantage of #define is that it guarantees constness and therefore there will be no backing variable.
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)
It is a compiler limitation, and the reason for that limitation is given by Eric Lippert here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With