Particularly the symbols ? : And how can I use them in other ways
Console.WriteLine("The rectangle with edges [{0},{1}] is {2}a square" ,
r3.Edge1, r3.Edge2, (r3.IsSquare()) ? "" : "not ");
Particularly the symbols ? : And how can I use them in other ways
Console.WriteLine("The rectangle with edges [{0},{1}] is {2}a square" ,
r3.Edge1, r3.Edge2, (r3.IsSquare()) ? "" : "not ");
Simply said conditional operator (?) does following,
If condition is
true
, first_expression is evaluated and becomes the result. If condition isfalse
, second_expression is evaluated and becomes the result
And inputs are given in following format,
condition ? first_expression : second_expression;
In your case parameters are as follow ,
condition = r3.IsSquare() // <= return a Boolean I guess
first_expression = "" // Empty string
second_expression = not // word `not`
So in your case what does code (r3.IsSquare()) ? "" : "not ")
does,
r3
is a square, output is ""
which is empty string.r3
is not a square , output is the word not
Note that method IsSquare()
called upon r3
should return a Boolean (true or false) value.
Same condition evaluated on a console program,
// if r3.IsSquare() return true
Console.WriteLine((true ? "" : "not")); // <= Will out an empty
// if r3.IsSquare() return false
Console.WriteLine((false ? "" : "not")); // will out the word `not`
Console.ReadKey();
It's a ternary operator. The basic way it works is like this:
bool thingToCheck = true;
var x = thingToCheck ? "thingToCheck is true" : "thingToCheck is false";
Console.WriteLine(x);
As others have said, ? is a ternary operator.
So to answer the actual question,
Console.WriteLine("The rectangle with edges [{0},{1}] is {2}a square" ,
r3.Edge1, r3.Edge2, (r3.IsSquare()) ? "" : "not ");
{0} and {1} will be replaced with the values of r3.Edge1 and r3.Edge2, respectively, when that line is written to the console. r3.IsSquare() is likely returning a boolean, so if it returns true, it'll write nothing (empty string "") but if it returns false, it'll write "not ".
So for example, the final result, assuming r3.IsSquare() returns false, would look like The rectangle with edges[3, 6] is not a square
, if it had returned true, then it would say The rectangle with edges[3, 6] is a square
.