Reputation: 3959
In C#
A book I am following advises this for set and get properties:
double pri_test;
public double Test
{
get { return pri_test; }
set { pri_test = value < 0 ? -value : value; }
}
I understand what value
is doing, its the input value from something outside using the property, however I don't understand the use of -value
and the ?
symbol and :
Could someone explain what this means: value < 0 ? -value : value
?
Upvotes: 1
Views: 1804
Reputation: 7804
You are looking at the conditional operator.
See ?: Operator (C# Reference)
and ?: (Wikipedia)
(the latter link is very concise!)
You'll often see people refer to the conditional operator it as the ternary operator. This is because a ternary operator takes three operands in this case - the condition, and two expressions.
Pertaining to -value
, the prefix -
meerly negates the integer
int bar = 10;
int foo = -bar;
Console.Write(foo); //prints "-10".
Upvotes: 6
Reputation: 98750
From ?: Operator
condition ? first_expression : second_expression;
The
condition
must evaluate totrue
orfalse
. Ifcondition
istrue
,first_expression
is evaluated and becomes the result. Ifcondition
isfalse
,second_expression
is evaluated and becomes the result.
pri_test = value < 0 ? -value : value;
is equivalent to;
if( value < 0 )
{
pri_test = -value;
}
else
{
pri_test = value;
}
Upvotes: 4
Reputation: 136094
You've already gotten a few answers pointing you to the ternary operator, that accounts for half your question
Could someone explain what this means?
value < 0 ? -value : value
What that line is doing with value
is checking if it is negative, and if so turning it to a positive. If the value starts off positive, it just leaves it alone.
There is already a method in the .NET framework which does this: Math.Abs
. So that line could be re-written as
pri_test = Math.Abs(value);
Upvotes: 4
Reputation: 680
value < 0 ? -value : value
is equals to this
if(value < 0)
{
pri_test = -value;
}
else
{
pri_test = value;
}
Upvotes: 1
Reputation: 60694
Here it is used to take the absolute value of a number. So if the number is negative. They take the number negated, that results in the positive number ( minus multiplied by minus is plus).
The other answers deal with the ?: ternary operator, but I would change the code to read like this in the setter:
set { pri_test = Math.Abs(value); }
Much more readable.
Upvotes: 1