Reputation: 41
Hi I have a problem like
bool isCompleted = true;
if(isCompleted){x= 5}
so i want use above code using ternary operator without using return or assignment like
isCompleted ? int x = 5 : <do nothing>;
So is it possible to use ternary operator without using return or assignment?
Thanks.
Upvotes: 0
Views: 3482
Reputation: 314
You want to set x to 5 if true. Otherwise keep x value?
x = isCompleted ? 5: x:
Upvotes: 0
Reputation: 3204
Try using it like this :
x = isCompleted ? intValue(if true) : intValue(if false);
Since you have declared x
as int
, you will have to provide the values in int
irrespective of the condition evaluated. Any other type value you use wont work here. Hence the false
that you wrote is wrong. You might want to provide an int
value there.
Incase if you want to perform some code logic based on bool conditions, you might want to use if...else
here as that will help you do more than just assigning some values to variables.
Hope this helps.
Upvotes: 3
Reputation: 23
You need the assignment prior to the boolean.
x = isCompleted ? 5: 0;
Secondly, you have a type error. The above will set x=5 if isCompleted = true otherwise it will set x=0
isComplete ? 5 :false
Will fail to compile as you can't assign a boolean to an int.
Upvotes: 2
Reputation: 2781
Read about ternary operator's syntax (MSDN):
The conditional operator (?:) returns one of two values depending on the value of a Boolean expression.
So your code must be rewriten as:
x = isCompleted ? 5 : 0;
Upvotes: 1