0
Can someone explain how the "?" operator works?
like to write a simple code which works with that operator
3 odpowiedzi
+ 2
I think you are referring to the "ternary operator". It works like this:
condition? return_if_true : return_if_false
for example:
if (age > 18){
Console.Write("go");
} else {
Console.Write("don't go");
}
can be rewritten as:
Console.Write(age > 18? "go" : "don't go");
In this case, the ternary operator will return "go" if the condition is true and "don't go" if it is false, and pass that to the Write() function.
+ 1
idk c# syntax but in js its like this:
(condition)? task1 : task2;
and what it does is this:
If the condition is true do task1 else do task2
Example:
(3>5)? alert("true") : alert("false");
output: false
I suppose it's somewhat similar syntax in c#.
It's basically an if else block in just one line.
It may significantly shorten your code but it also significantly decreases readability.
So use it with care if you are going to revisit your code after some time or if you have to explain it to someone else.
+ 1
wow. thanks a lot. you made me understand