C Sharp

Unary Operators

There are two unary operators, plus and minus. The unary minus operator indicates to the compiler that the operand is to be made negative. Therefore, the following would result in a being equal to - 42: -

using System;
using System;
class Unary1App
{
    public static void Main()
    {
        int a = 0;
        a = -42;
        Console.WriteLine("{0}", a);
    }
}

However, ambiguity creeps in when you do something like this: -

using System;
class Unary2App
{
    public static void Main()
    {
        int a;
        int b = 2;
        int c = 42;
        a = b * -c;
        Console.WriteLine("{0}", a);
    }
}

The a = b * -c can be bit confusing. Once again, the use of parentheses helps to make this line of code much clearer: -

// With parentheses, it's obvious that you're multiplying
// b by the negative of c.
a = b * (-c);

If the unary minus returns the negative value of an operand, you'd think that the unary plus would return the positive value of an operand. However, the unary plus does nothing but return the operand in its original form, thereby having no effect on the operand. For example, the following code will result in the output of - 84: -

using System;
class Unary3App
{
    public static void Main()
    {
        int a;
        int b = 2;
        int c = -42;
        a = b * (+c);
        Console.WriteLine("{0}", a);
    }
}

To retrieve the positive form of an operand, use the Math.Abs function. The following will produce a result of 84: -

using System;
class Unary4App
{
    public static void Main()
    {
        int a;
        int b = 2;
        int c = -42;
        a = b * Math.Abs(c);
        Console.WriteLine("{0}", a);
    }
}

One last unary operator that I'll mention briefly is the (T)x operator. This is a form of the parenthesis operator that enables a cast of one type to another type. Because this operator can be overloaded by virtue of creating a user-defined conversion, it's covered in Chapter 13, "Operator Overloading and User-Defined Conversions." -