Fun example, thanks!
The operator you're overriding here is "-". However, from your example, it looks like you're really thinking "--". The "-" operator should return a value, but not affect the object it's working on. The incrementors will affect the object.
Taking your example, this might be clearer.
csharp
using System;
class Space {
public int x, y, z;
public Space(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
// rather than a display method, I'm going to override the ToString method.
public override string ToString() {
return string.Format("({0},{1},{2})", x, y, z);
}
// this is the - operator
//note that nothing happens to the object passed
public static Space operator -(Space s) {
return new Space(-s.x, -s.y, -s.z);
}
// this is the -- operator
// note that we operate on the passed value
// and then pass it back.
public static Space operator --(Space s) {
s.x = -s.x;
s.y = -s.y;
s.z = -s.z;
return s;
}
}
class SpaceTest {
public static void Main() {
Space s = new Space(-10, 20, 30);
// starting value
Console.WriteLine(s); // prints (-10,20,30)
// value is returned
Console.WriteLine(-s); // prints (10,-20,-30)
// but doesn't affect the object
Console.WriteLine(s);// prints (-10,20,30)
// this does affect the object
--s;
Console.WriteLine(s);// prints (10,-20,-30)
}
}
Hope this helps.