// Collection of code snippets by Arne Vajhøj // (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) using System; public class IntPair { public int V1 { get; set; } public int V2 { get; set; } public static IntPair operator +(IntPair o1, IntPair o2) { return new IntPair { V1 = o1.V1 + o2.V1, V2 = o1.V2 + o2.V2 }; } public static IntPair operator -(IntPair o1, IntPair o2) { return new IntPair { V1 = o1.V1 - o2.V1, V2 = o1.V2 - o2.V2 }; } public override string ToString() { return $"({V1},{V2})"; } } public class DoublePair { public double V1 { get; set; } public double V2 { get; set; } public static DoublePair operator +(DoublePair o1, DoublePair o2) { return new DoublePair { V1 = o1.V1 + o2.V1, V2 = o1.V2 + o2.V2 }; } public static DoublePair operator -(DoublePair o1, DoublePair o2) { return new DoublePair { V1 = o1.V1 - o2.V1, V2 = o1.V2 - o2.V2 }; } public override string ToString() { return $"({V1},{V2})"; } } /* This does not compile: public class Pair { public T V1 { get; set; } public T V2 { get; set; } public static Pair operator +(Pair o1, Pair o2) { return new Pair { V1 = o1.V1 + o2.V1, V2 = o1.V2 + o2.V2 }; } public static Pair operator -(Pair o1, Pair o2) { return new Pair { V1 = o1.V1 - o2.V1, V2 = o1.V2 - o2.V2 }; } public override string ToString() { return $"({V1},{V2})"; } } */ public class Program { public static void Main(string[] args) { IntPair p1 = new IntPair { V1 = 1, V2 = 2 }; IntPair p2 = new IntPair { V1 = 3, V2 = 4 }; IntPair res12 = p1 + p2; Console.WriteLine("{0} + {1} = {2}", p1, p2, res12); DoublePair p3 = new DoublePair { V1 = 0.1, V2 = 0.2 }; DoublePair p4 = new DoublePair { V1 = 0.3, V2 = 0.4 }; DoublePair res34 = p3 + p4; Console.WriteLine("{0} + {1} = {2}", p3, p4, res34); } }