I am a new starter in programming. What do the quesion mark and the colon mean below?
string str= "PHP Tutorial";
Console.WriteLine((str.Substring(1, 2).Equals("HP") ? str.Remove(1, 2) : str));
CodePudding user response:
This is a shorthand for an if-Statement.
The same could also be written like this:
string str = "PHP Tutorial";
if(str.Substring(1, 2).Equals("HP")) {
Console.WriteLine(str.Remove(1, 2));
} else {
Console.WriteLine(str);
}
CodePudding user response:
a = b ? c : d;
is shorthand for:
if (b)
a = c;
else
a = d;
The C# ternary operator evaluates the first operand, which must be a Boolean expression, and returns the second operand if it's true
and the third operand if it's false
. The second and third operands must be of the same type so that the overall return type of the expression is known.
CodePudding user response:
C# includes a decision-making operator ?: which is called the conditional operator or ternary operator. It is the short form of the if else
conditions.
condition ? statement 1 : statement 2
The following example demonstrates the ternary operator:
int x = 20, y = 10;
var result = x > y ? "x is greater than y" : "x is less than y";
Console.WriteLine(result);
output:
x is greater than y
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/conditional-operator