Are there any advantages or benefits to using tertiary operators for if statements?
For example, is the following more efficient? Or considered better programming practice?
variable1 = string.IsNullOrEmpty(variable2) ? "string value" : "";
Compared to the following format:
if (string.IsNullOrEmpty(variable2))
{
variable1 = "string value"
} else
{
variable1 = "";
}
The ternary operator is more concise: less typing and quicker to read. The compiled IL code or the JITted native code are likely to be identical. If not, any performance differences are almost certain to be virtually unmeasurably small. Therefore, source code quality is the only real consideration in making the decision.
“Tertiary” means “third in importance”; “ternary” means “having three parts.”
I personally prefer the term “conditional operator” because it’s entirely possible that someone will invent another ternary operator in the future. Imagine if we had to call
+the “first binary operator” and-the “second binary operator”!