Summary#
var declares a local and infers its type from the initializer — the same var as C#. The local is statically
typed: var total = 0m; is a decimal and always will be. var saves you writing the type, it does not make the
value dynamic.
Signature#
var <name> = <expression>; // the type comes from the expressionDescription#
It is inference, not dynamism#
entity Order {
[Required] string Code;
decimal Total;
}
void Locals() {
var count = 0; // int
var total = 0m; // decimal — the m suffix matters
var label = "orders"; // string
var order = Order.Single(o => o.Code == "A1"); // Order
var codes = Order.Where(o => o.Total > 0).ToList(); // Order[]
}Assigning something else later is a compile error, exactly as in C#.
var total = 0; is an int, and it will bite you#
The single most common slip. 0 is an int, so var total = 0; gives you an integer accumulator — and adding
decimals to it will not compile, or worse, will truncate the arithmetic you meant to keep:
decimal SumTotals() {
var total = 0m; // decimal — correct
foreach (var o in Order.Where(o => o.Total > 0).ToList()) {
total += o.Total;
}
return total;
}Write 0m whenever the accumulator holds money. If you want the type stated outright, use a
typed local — decimal total = 0; — which says the same thing more loudly.
When to prefer the explicit type#
Use var when the initializer already makes the type obvious (var order = Order.Single(…)). Write the type out when
it does not, or when the type is the thing the reader needs to know — an accumulator, a boundary, a value someone will
change later.
See also#
- Typed locals — declaring the type explicitly instead
- const — a local that cannot change
- Numeric types & literal suffixes — why
0and0mare different types