Joseph
Joseph

Reputation: 3959

What does this mean/do? "value < 0 ? -value : value;"

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

Answers (5)

User 12345678
User 12345678

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

Soner G&#246;n&#252;l
Soner G&#246;n&#252;l

Reputation: 98750

From ?: Operator

condition ? first_expression : second_expression;

The condition must evaluate to true or false. If condition is true, first_expression is evaluated and becomes the result. If condition is false, 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

Jamiec
Jamiec

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

Mirza Danish Baig
Mirza Danish Baig

Reputation: 680

value < 0 ? -value : value 

is equals to this

if(value < 0) 
{

   pri_test = -value;

}
else
{
   pri_test = value;
}

Upvotes: 1

&#216;yvind Br&#229;then
&#216;yvind Br&#229;then

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

Related Questions