7.3: Ternary Expressions
In this module we'll study ternary expressions.
File Location
Right click on the solution you made in the first module.
Go to Add > New Project and select Console App (.NET Framework).
Name it
07_conditionals_ternary_expressions
.Write your code for this module within
Program.cs
of that project.
Ternary Expressions
Ternary Expressions are simply a different way to write if statements. They provide less lines of code, reduce nesting, and therefore help your program run faster and more efficiently.
Example:
Discussion
In the above lines of code, we have an expression asking if the number is 7.
We then use the ternary operator
?
to identify that a ternary expression is coming.If the expression is true, we return
The number is 7.
We use a colon to separate options. Think of the left side as the
if
and the right side as theelse
.If the expression is false, we return
The number is not 7.
Here is the basic format of a ternary expression:
((question) ? do if true : do if false);
Further Practice
Try to make some conditional statements of your own. Don't worry about making them too complicated. Try any or all of the following, and when you feel like you're ready, move on to the next module:
Switch Cases
If and else if statements
Ternary Expressions
Last updated