c# ternary
/* In C#, if condition is true, the first expression is evaluated and becomes
the result; if false, the second expression is evaluated and becomes
the result. */
// The syntax of ternary operator is:
Condition ? Expression1 : Expression2;
// Here is a simple example:
string color = "blue";
string result = (color == "blue") ? "blue" : "NOT blue";
Console.WriteLine(result);
// Here is a really good diagram of the ternary operator:
// https://www.codebuns.com/wp-content/uploads/2018/09/ternary-operator.png
// The normal if else statment is the same as the ternary operator.
// If else statement:
if (number % 2 == 0)
{
isEven = true;
}
else
{
isEven = false;
}
// Ternary operator:
isEven = (number % 2 == 0) ? true : false ;
// Another example use of the ternary operator:
class Ternary
{
public static void Main(string[] args)
{
int number = 2;
bool isEven;
isEven = (number % 2 == 0) ? true : false ;
Console.WriteLine(isEven);
}
} // OUTPUT: True
3.86
7
condition ? consequent : alternative
Thank you!
7
0
3.89
9
condition ? consequent : alternative
Thank you!
9
0
3.75
4
is this condition true ? yes : no
Thank you!
4
0
5
1
(condition ? [true value] : [false value])
int x = a ? b : c;
Thank you!
1
0
0
0
// ---------------- Syntax of Ternary Operators ----------------- //
string stateOfMatter;
int temperature = 23;
// ---- For just one condition ---- //
stateOfMatter = temperature < 0 ? "Solid": "Liquid";
// If temperature is below zero, then stateOfMatter is solid, otherwise
// it will be liquid
// ---- For more conditions ---- //
stateOfMatter = temperature < 0 ? "Solid" : (temperature > 100 ? "Gas" : "Liquid");
Thank you!
0
0
Are there any code examples left?
New code examples in category C#