question mark inside C# syntax [duplicate]
Possible Duplicate:
Benefits of using the conditional ?: (ternary) operator
hi, I'm viewing this freesource library and I saw this weird - at least for me - syntax
*currFrame = ( ( diff >= differenceThreshold ) || ( diff <= differenceThresholdNeg ) ) ? (byte) 255 : (byte) 0;
currFrame is of type byte
diff, differenceThreshold and differenceThresholdNeg are of type Int.
What does the question mark do ? , what is this weird assign sentence suppose to mean ?
开发者_StackOverflowThanks in advance
The conditional operator (?:) returns one of two values depending on the value of a Boolean expression. Following is the syntax for the conditional operator.
condition ? first_expression : second_expression;
C# reference: http://msdn.microsoft.com/en-us/library/ty67wk28.aspx
In your case currFrame will be assigned a value of 255 if ( diff >= differenceThreshold ) || ( diff <= differenceThresholdNeg )
is true
, otherwise value 0 will be assigned.
this is the same as
if(( diff >= differenceThreshold ) || ( diff <= differenceThresholdNeg ) )
currFrame = (byte) 255
else
currFrame = (byte) 0
It is the conditional operator.
?: Operator (C# Reference):
The conditional operator (?:) returns one of two values depending on the value of a Boolean expression. The conditional operator is of the form
condition ? first_expression : second_expression;
'?:' is a conditional operator, you can read about it here: http://msdn.microsoft.com/en-us/library/ty67wk28(v=vs.80).aspx
This is a ternary operator (see MSDN). It follows the following syntax:
result = condition ? result_if_condition_true : result_if_condition_false
if ( diff >= differenceThreshold ) || ( diff <= differenceThresholdNeg ) )
*currFrame = (byte) 255;
else *currFrame = (byte) 0;
精彩评论