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#
if (<bool>) { … }
else if (<bool>) { … }
else { … }Description#
How do I write an if / else chain?#
string Band(decimal total) {
if (total >= 1000m) {
return "large";
} else if (total >= 100m) {
return "medium";
} else {
return "small";
}
}The condition is a bool, always#
There is no "non-empty string is true" and no "non-zero is true". Say what you mean:
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 — ?:#
For a value rather than a branch, ?: reads better than four lines of if:
string Label(bool paid) {
return paid ? "paid" : "outstanding";
}Too many else ifs? — reach for switch#
A chain of else if over the same value is usually a switch — especially over an
enum, where the compiler can then tell you when you have missed a case.