Search code examples
c#tuples

Can you add two (int) tuples together?


Something like:

var Tuple1 = (x:2,y:4);
var Tuple2 = (x:0,y:-1);
var Tuple3 = Tuple1 + Tuple2;
// desired output: (x:2,y:3)

Is there a simple way, or must I do something like:

Tuple3.x = Tuple1.x + Tuple2.x;
Tuple3.y = Tuple1.y + Tuple2.y;

I'm also open to using another structure instead of tuple.


Solution

  • Without any extra work the one-liner would be:

    var tuple1 = (x:2,y:4);
    var tuple2 = (x:0,y:-1);
    var tuple3 = (x: tuple1.x + tuple2.x, y: tuple1.y + tuple2.y);
    

    Another option is to create a extension method Add (this method leverages two other features - generics and generic math, the latter being available since .NET 7):

    public static class TupleExts
    {
        public static (TX X, TY Y) Add<TX, TY>(this (TX X, TY Y) left, (TX X, TY Y) right)
            where TX : IAdditionOperators<TX, TX, TX>
            where TY : IAdditionOperators<TY, TY, TY> =>
            (left.X + right.X, left.Y + right.Y);
    }
    

    And usage:

    var tuple1 = (x:2,y:4);
    var tuple2 = (x:0,y:-1);
    var tuple3 = tuple1.Add(tuple2);
    

    But since you wrote that you are not limited to tuples then you can define your own type and overload the + operator. See the Operator overloading documentation. Something to start with:

    public class Point
    {
        public int X { get; set; }
        public int Y { get; set; }
    
        public static Point operator +(Point left, Point right) => new Point
        {
            X = left.X + right.X,
            Y = left.Y + right.Y
        };
    }
    

    Then you will be able to use the + operator:

    var p = new Point { X = 2, Y = 4 } + new Point { X = 0, Y = -1 };