2.6: Ternary Operators
In this module we'll take a look at ternary operators.
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
0.02_Ternary_Operators
Write your code for this module within
Program.cs
of that project
About
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.
class Program
{
static void Main(string[] args)
{
int number = 10;
//1 //2 //3 //4
string response = ((number == 7) ? "The number is 7." : "The number is not 7.");
Console.WriteLine(response);
}
}
Discussion
We have an expression asking if the number is 7.
Then, we use the ternary operator
?
to allow us to set up a comparison.Before the colon, we show this if it is true.
If false, the value is what we have after the colon.
Here is the basic format of a ternary expression:
((value that we're checking for true or false) ? do this if true : do this if false);
Next: Ternary Expressions
Last updated