views:

61

answers:

4

Are following ways are same.(Considering the evaluation time)

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

condition1 ? code1 : code2

Are they just syntactically different?

It may seem a stupid question.But I want to clear my doubt.

A: 

Yes & Yes.

Only profit is to save lines of code.

Faruz
Not the only one. The second variant can be used to bind a reference to two different object depending on condition, the first one can't be used for that.
sharptooth
Right, forgot about that.
Faruz
A: 

Well ... In the former case, you can have any amount or type (expression vs statement) of code in place of code1 and code2. In the latter case, they must be valid expressions.

unwind
+1  A: 

Yes, these are two different syntactical forms and will work identically and most likey identical code will be emitted by the compiler.

sharptooth
+4  A: 

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

For example, if you have a following statement:

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

Using a ternary operator, you will write:

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

Note how the first example executes a statement based on a condition, while the second one returns a value based on a condition.

Groo