Your second method is actually written incorrectly: you’re adding the .x
property of rhs
to everything. I’m going to assume that was a simple mistake, and you meant to have the same behavior between the two methods.
These two examples call different constructor overloads, which you haven’t included code for. If we can assume that the first example’s constructor just sets the x
, y
, and z
properties on that object, then the only difference should be that the first one needs to load the value from the .x
, .y
, and .z
properties before it can set them, so it will have slightly slower performance.
However, this performance difference will be negligible, so unless this is a performance-critical piece of code, you would do better to focus on readability.
Personally, I’d do this:
public Vector(int x, int y, int z)
{
this.x = x;
this.y = y;
this.z = z;
}
public static Vector operator + (Vector lhs, Vector rhs)
{
return new Vector(
rhs.x + lhs.x,
rhs.y + lhs.y,
rhs.z + lhs.z;
);
}
4
solved C# operator overloading performance [closed]