Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you add two (int) tuples together?

Tags:

c#

tuples

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.

like image 895
akTed Avatar asked Dec 02 '25 22:12

akTed


2 Answers

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 };
like image 70
Guru Stron Avatar answered Dec 05 '25 11:12

Guru Stron


There's nothing built-in for Tuples to support this natively. You will have to write the code yourself.

But you can hide the code in an extension method if you want:

public static (int, int) Add(this (int, int) t1, (int, int) t2) =>  (t1.Item1+t2.Item1, t1.Item2+t2.Item2);

Then you can do this:

var Tuple3 = Tuple1.Add(Tuple2);

Obviously this won't scale well to support tuples of other types or length.

like image 31
Joel Coehoorn Avatar answered Dec 05 '25 12:12

Joel Coehoorn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!