# var

> Declares a local whose type is inferred from its initializer, exactly as in C#. The local is still statically typed — var is about not repeating the type, never about being dynamic.

<!-- id: function-var · area: function · stability: stable · html: https://osysharp.com/reference/function/var/ -->

## Summary        {#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      {#signature}
```osy syntax
var <name> = <expression>;     // the type comes from the expression
```

## Description    {#description}

### It is inference, not dynamism   {#inference}
```osy title="what each var infers" test app=function-var
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   {#zero-trap}
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:

```osy title="seed a money accumulator with 0m, not 0" test app=function-var
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](https://osysharp.com/reference/function/typed-locals/) — `decimal total = 0;` — which says the same thing more loudly.

### When to prefer the explicit type   {#when-explicit}
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       {#see-also}
- [Typed locals](https://osysharp.com/reference/function/typed-locals/) — declaring the type explicitly instead
- [const](https://osysharp.com/reference/function/const/) — a local that cannot change
- [Numeric types & literal suffixes](https://osysharp.com/reference/function/numeric-literals/) — why `0` and `0m` are different types
