Summary#
const declares a value fixed at compile time. The initializer must be a constant expression — a literal, or
arithmetic over other constants — and the value is folded into every place it is used.
It goes in any of four places, as in C#:
const int EatSoonDays = 90; // top level — every function and page in the app can read it
component Home() { const int Rows = 20; … } // one component
int F() { const int Limit = 5; … } // one body
class Rules { public const int Retries = 3; } // on a class⭐ Because it FOLDS, a const goes anywhere a literal goes — including inside a query predicate:
const int EatSoonDays = 90;
live var due = Item.Where(i => i.Days > EatSoonDays).Count(); // becomes `days > 90`, and lowers to SQLA helper function cannot: Item.Where(i => i.Days > EatSoonDays()) is refused, because a predicate becomes SQL and
SQL cannot call back into your code. That is the difference between the two, and it is the reason to reach for
const when the value never varies.
Its real job is not performance. It is naming a magic number so the next person does not have to guess what 0.2
meant.
Signature#
const <Type> <NAME> = <compile-time constant>;Description#
How do I give a number a name?#
decimal WithVat(decimal amount) {
const decimal VatRate = 0.2m;
return Math.Round(amount * (1 + VatRate), 2);
}amount * 1.2m would compute the same total and tell the reader nothing. Six months later, VatRate is the
difference between a change that takes a minute and one that takes an afternoon of grepping for 1.2.
What may a const initializer contain?#
The initializer is evaluated by the compiler, so it cannot read a parameter, a row, or anything decided at run time. Constants may be built from other constants:
decimal Fee(decimal amount) {
const decimal Base = 2m;
const decimal Percent = 0.015m;
const decimal Cap = Base + 50m; // fine — arithmetic over constants
var fee = Base + amount * Percent;
return fee > Cap ? Cap : fee;
}Something that depends on a value only known at run time is not a const — it is a var.
const vs var#
const | var | |
|---|---|---|
| Value known at | compile time | run time |
| Can be reassigned | no | yes |
| Good for | a named fixed number, a threshold, a rate | everything else |
See also#
- var — a local whose value is computed at run time
- Typed locals — an explicitly typed local you can reassign
- Numeric types & literal suffixes — literal suffixes (
m,L) and what they mean