# if / else

> Conditional branching, exactly as in C#. The condition must be a bool — there is no truthiness, so a null or a number is not a condition.

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

## Summary        {#summary}
`if` / `else if` / `else`, exactly as in C#. The condition must be a **`bool`** — there is no truthiness. A string, a
number or a null is not a condition, and writing one is a compile error rather than a subtle bug.

## Signature      {#signature}
```osy syntax
if (<bool>) { … }
else if (<bool>) { … }
else { … }
```

## Description    {#description}

### How do I write an `if` / `else` chain?   {#branching}
```osy title="grading a total" test app=function-if
string Band(decimal total) {
  if (total >= 1000m) {
    return "large";
  } else if (total >= 100m) {
    return "medium";
  } else {
    return "small";
  }
}
```

### The condition is a bool, always   {#no-truthiness}
There is no "non-empty string is true" and no "non-zero is true". Say what you mean:

```osy title="testing for a value" test app=function-if
entity Contact {
  [Required] string Name;
  string Phone;
}

string Reach(Contact c) {
  if (c.Phone != null) { return c.Phone; }      // not `if (c.Phone)`
  return "no phone";
}

bool IsBig(int count) {
  if (count > 0) { return true; }               // not `if (count)`
  return false;
}
```

This is stricter than a dynamic language, and it is the strictness that pays: `if (count)` and `if (count > 0)` mean
the same thing right up until `count` is `-1`.

### Choosing a value rather than a branch — `?:`   {#ternary}
For a value rather than a branch, `?:` reads better than four lines of `if`:

```osy title="choosing a value" test app=function-if
string Label(bool paid) {
  return paid ? "paid" : "outstanding";
}
```

### Too many `else if`s? — reach for `switch`   {#many-cases}
A chain of `else if` over the same value is usually a [`switch`](https://osysharp.com/reference/function/switch/) — especially over an
[enum](https://osysharp.com/reference/enum/declaration/), where the compiler can then tell you when you have missed a case.

## See also       {#see-also}
- [switch](https://osysharp.com/reference/function/switch/) — branching over many values of one expression
- [enum](https://osysharp.com/reference/enum/declaration/) — the closed sets a switch is exhaustive over
- [while](https://osysharp.com/reference/function/while-loop/) — repeating while a condition holds
