Search code examples
c#unary-operator

Is it safe to use the unary plus operator?


I saw code that goes like this:

double d = GetDouble();
DoSomething(+d);
DoSomething(-d);

I know in it is potentially dangerous and not recommended in C++ to use the unary + just to emphasize that the value is positive. <EDIT>"just to emphasize that the value is positive" was a mental shortcut. I know it doesn't make a negative value positive.</EDIT>

The C# language reference doesn't say much about it:

The unary + operator returns the value of its operand.

There is a question on SO about this, but it is tagged with C, C++ and C#, and none of the answers clearly mentions C#.


Solution

  • As this answer of the question you linked says, unary + in C(++) does do something, and is not necessarily a no-op. This is true in C# too.

    C# only has these unary + operators (See spec):

    int operator +(int x);
    uint operator +(uint x);
    long operator +(long x);
    ulong operator +(ulong x);
    float operator +(float x);
    double operator +(double x);
    decimal operator +(decimal x);
    

    So if x is a short, +x would be of type int, because the first operator is selected by overload resolution. As a result, something like this does not compile:

    short x = 1;
    short y = +x;
    

    This also affects overload resolution, among other things. Just like the code presented in this answer, if you do:

    public class C {
        public static void Foo(int x) {
            Console.WriteLine("int");
        }
        
        public static void Foo(short x) {
            Console.WriteLine("short");
        }
    }
    

    C.Foo(x) where x is a short will print short, but C.Foo(+x) will print int.

    Does this situations like the above happens often enough that makes +x a "bad" or "unsafe" practice? That is for you to decide.

    Of course, if x is of a custom struct/class type, then +x could do basically anything. Unary + is overloadable.