Overload of +/- unary operators

When you overload - unary operators, for an immutable type, you can write it like this:

public static Point3 operator - (Point3 p) { return new Point3 (-pX, -pY, -pZ); } 

But for a + unary operator, how to implement it? Like this:

 public static Point3 operator + (Point3 p) { return p; } 

or like this:

 public static Point3 operator + (Point3 p) { return new Point3 (p); } 
+4
source share
6 answers

In any case, this is normal. You do not mutate the source object with one of two methods.

If you call string.substring(0, string.length()) , there is no reason why the original string cannot be returned.

The only contract that you sign with immutability is that after creating the object, it does not change.

+7
source

If the structure is immutable, you can choose, I would return the original value.

If changed, return a new one.

+2
source

I cannot imagine a case where this would change an immutable type. It is best to return p , the principle of least surprise .

+2
source

In my opinion, this depends on the implementation of Point3.Equals ().

Consider the following code:

 Dictionary<Point3, string> cache; Point3 pointA = new Point3(1, 2, 3); Point3 pointB = new Point3(1, 2, 3); cached[pointA] = "Value Aaa"; cached[pointB] = "Value Bbb"; Console.WriteLine(cached[pointA]); Console.WriteLine(cached[pointB]); 

If Point3 has reference semantics (pointA.Equals (pointB) when they are the same object), this will output:

 Value Aaa Value Bbb 

If Point3 has semantics of values ​​(pointA.Equals (pointB) when their x, y, and z values ​​are equal), this will output:

 Value Bbb Value Bbb 

With semantics of meaning, it doesn't really matter if you create a new object or not. Perhaps you just return the same to avoid creating garbage.

If your type has reference semantics, you probably want the unary plus to create a new object, so that it behaves just like other operators.

+2
source

I would prefer the second method (although it would be slower), but assuming Point3 is a three-dimensional point, this will probably be a struct not a class .

+1
source

Um ....

 public static Point3 operator - (Point3 p) { return new Point3 (-p); } 

correct me if I'm wrong, but didn't this create infinite recursion? You call the unary (-) operator inside the unary (-) operator method.

I think you want to do this:

 public static Point3 operator - (Point3 p) { return new Point3 (-(pX), -(pY), -(pZ)); // EDIT: Added parens for the sake of explicity. I don't recall the operator precedence in this case. } 

Assuming you have such a constructor and properties in your Point3 class.

+1
source

All Articles