Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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#.

like image 824
michuu Avatar asked Nov 17 '25 11:11

michuu


1 Answers

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.

like image 91
Sweeper Avatar answered Nov 19 '25 23:11

Sweeper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!