Added a Code Example (#24153)
* Added a Code Example Added an if...else equivalent of a ternary operator as an example to help readers gain a better understanding of how ternary operators work. * Update index.md
This commit is contained in:
committed by
The Coding Aviator
parent
534a484003
commit
763d6658b1
@ -3,7 +3,8 @@ title: Ternary operator
|
||||
---
|
||||
|
||||
# Ternary operator (`?:`)
|
||||
Ternary operator returns one of the two expressions based on a condition. It can be used as a shortcut for if...else statement.
|
||||
|
||||
The ternary operator returns one of the two expressions based on a condition. It can be used as a shortcut for if...else statement.
|
||||
|
||||
## Syntax
|
||||
```
|
||||
@ -30,6 +31,23 @@ string str = hasFreeSweets ? "Free sweets!" : "No free sweets.";
|
||||
Console.WriteLine(str);
|
||||
```
|
||||
|
||||
## Equivalent if...else Statement
|
||||
```
|
||||
// initialize - set true or false here to view different result
|
||||
bool hasFreeSweet = false;
|
||||
|
||||
string str;
|
||||
|
||||
if(hasFreeSweet){
|
||||
str = "Free sweet!";
|
||||
} else {
|
||||
str = "No free sweet.";
|
||||
}
|
||||
|
||||
//output in console
|
||||
Console.WriteLine(str);
|
||||
```
|
||||
|
||||
## Output
|
||||
```
|
||||
if hasFreeSweets == true
|
||||
|
Reference in New Issue
Block a user