tags:

views:

265

answers:

6

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

public static Point3 operator - (Point3 p)
{
    return new Point3 (-p.X, -p.Y, -p.Z);
}

But for the + unary operator, how should you 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);
}
+1  A: 

I would prefer the second method (although it would be slower), but assuming Point3 is a 3D point, it should probably be a struct not a class.

Zifre
+5  A: 

Either way is fine. You are not mutating the original object in either of the two methods.

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

The only contract you sign with immutability is that once an object is created, it doesn't change.

jjnguy
+2  A: 

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

If mutable, return a new one.

Lasse V. Karlsen
+2  A: 

I can't imagine a case where it would make a difference to an immutable type. Best to just return p, by principle of least surprise.

Mark
+2  A: 

In my opinion it depends on 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 value semantics (pointA.Equals(pointB) when their x, y and z values are equal), this will output:

Value Bbb
Value Bbb

With value semantics it would not really matter if you create a new object or not. You could probably 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 the same way as the other operators.

Hallgrim
A: 

Um....

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

correct me if I'm wrong, but doesn't that set up an infinite recursion? You're calling the unary (-) operator inside the unary (-) operator method.

It seems to me you're going to want to do this:

public static Point3 operator - (Point3 p)
{
    return new Point3 (-(p.X), -(p.Y), -(p.Z)); 
    // 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 on your Point3 class.

Randolpho
Thanks, yeah I didn't pay attention to that, got stuck at the idea I guess.
Joan Venge