Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I declare a constant using var in C#? [duplicate]

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?

like image 758
bevacqua Avatar asked May 26 '11 00:05

bevacqua


People also ask

How do you declare a constant variable in C?

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.

Can we use constant in C?

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.

Why should you not use #define to declare a constant?

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.


2 Answers

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)

like image 125
SLaks Avatar answered Oct 05 '22 09:10

SLaks


It is a compiler limitation, and the reason for that limitation is given by Eric Lippert here

like image 21
Martin Booth Avatar answered Oct 05 '22 10:10

Martin Booth