If / else vs ternary operator

Given the time of the assessment, two equivalents follow?

if(condition1)
{
    //code1
}
else
{
    //code2
}

condition1 ? code1 : code2

Or are they just syntactically different?

+5
source share
4 answers

The difference is that the last station can be used to return a value based on the condition.

For example, if you have the following statement:

if (SomeCondition())
{
    text = "Yes";
}
else
{
    text = "No";
}

Using the ternary operator, you will write:

text = SomeCondition() ? "Yes" : "No";

Notice how the first example executes a statement based on a condition, and the second returns a value based on a condition.

+11
source

... code1 code2 ( vs statement) . .

+4

Yes and yes.

The only profit is to save lines of code.

+3
source

Yes, these are two different syntactic forms and will work the same, and the most similar code will be emitted by the compiler.

+1
source