C# › Indexers & Operator Overloading

How would you implement a fluent, chainable custom '+' operator overload for building an immutable Vector3 math library, and what performance consideration applies for structs?

Advanced

Answer

Since Vector3 is typically implemented as a struct for value-semantics and performance, EVERY operator overload should return a NEW Vector3 instance (preserving immutability) rather than mutating either input — and because structs are copied by value, operator overloads on small structs are generally cheap, avoiding heap allocation entirely, unlike an equivalent class-based implementation.
public readonly struct Vector3 {
  public readonly double X, Y, Z;
  public Vector3(double x, double y, double z) { X = x; Y = y; Z = z; }
  public static Vector3 operator +(Vector3 a, Vector3 b) => new(a.X + b.X, a.Y + b.Y, a.Z + b.Z);
  public static Vector3 operator *(Vector3 v, double scalar) => new(v.X * scalar, v.Y * scalar, v.Z * scalar);
}
Vector3 result = (v1 + v2) * 2.0; // fully chainable, zero heap allocation
Real-world example Building a high-performance, allocation-free 3D vector math library for a game engine or physics simulation.

Common follow-ups: Why is 'readonly struct' specifically recommended here, beyond just 'struct'?