#1,071 – The Unary Minus Operator

Unary operators are operators that affect a single operand.

The unary – operator is used to negate a numeric value.  (Subtract the value from zero).  The unary + operator does not affect a value, so is not worth mentioning.

            // Unary minus operator applied to constants
            int x = 5;
            int y = -5;
            Console.WriteLine("x={0}, y={1}", x, y);

            // Unary minus operator applied to variable
            x = -x;
            y = -y;
            Console.WriteLine("x={0}, y={1}", x, y);

1071-001

The unary operator also works with floating point and decimal values.

            double d = -4.2;
            float f = -4.2f;
            Console.WriteLine("d={0}, f={0}", d, f);

            decimal m = -0.01m;
            Console.WriteLine("m={0}", m);

1071-002

 

Advertisement