Reputation: 193
Hypothetical question. I have a custom object in my program, called GamePoint. It is properly defined and has all of its required members. What I'm wondering is if I can implement something similar to the following:
GamePoint p = new GamePoint(10, 10);
p += new GamePoint(15, 15);
//output: p = {25, 25}
Is there anyway to implement syntax like that?
Upvotes: 1
Views: 1257
Reputation: 54433
Assuming your GamePoint class is what I guess it is here you go:
class GamePoint
{
public int x { get; set; }
public int y { get; set; }
public GamePoint(int x_, int y_) {x=x_; y= y_;}
public static GamePoint operator +(GamePoint GamePoint1, GamePoint GamePoint2)
{
return new GamePoint(
GamePoint1.x + GamePoint2.x,
GamePoint2.y + GamePoint1.y);
}
public override string ToString()
{
return " (" + this.x.ToString() + "/" + this.y.ToString() + ") ";
}
}
Upvotes: 0
Reputation: 101701
Ofcourse you can, use operator overloading:
class GamePoint
{
private int v1;
private int v2;
public GamePoint(int v1, int v2)
{
this.v1 = v1;
this.v2 = v2;
}
public static GamePoint operator +(GamePoint a, GamePoint b)
{
return new GamePoint(a.v1 + b.v1, a.v2 + b.v2);
}
}
Upvotes: 7