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?
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?
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)
var
for constants, but it doesn't explain why you can't. –
Commingle const var
is dumb, but if var
is a convenience, then const
should be able to do the same thing: const s = "mystring"
. https://mcmap.net/q/242924/-type-inferring-a-constant-in-c –
Pruritus const auto i = 5
. It's not pointless or useless with more complex types. There's no reason why it couldn't work also in C# with var
. –
Table Constants without var:
const int Value1 = 1;
const int Value2 = 2;
Constants with var (anonymous type property values cannot be changed after creation):
var constants = new {
Value1 = 1,
Value2 = 2,
};
//use as constants.Value1
Since constants must be built-in numeric types or string
, you don't really save much; const int
is the same length as const var
and int
is probably the most common type of constant. Then there's double
which is really not all that long. If you have a lot of them to type, use the Alt selection feature ;-)
© 2022 - 2024 — McMap. All rights reserved.
const
is shorthand for "constant";var
is shorthand for "variable". Constants and variables are polar opposites, makingconst var
an oxymoron. – Redeemvar
are statically typed using type-inference (en.wikipedia.org/wiki/Type_inference) at compile time. – Grandpapa