How to write a user-defined operator in C#

1 Answer

0 votes
using System;

public class Point
{
    public int X { get; set; }
    public int Y { get; set; }

    public Point(int x, int y) {
        X = x;
        Y = y;
    }

    // Overloading the + operator (user-defined operator)
    public static Point operator +(Point p1, Point p2) {
        return new Point(p1.X + p2.X, p1.Y + p2.Y);
    }

    public override string ToString() {
        return $"({X}, {Y})";
    }
}

class Program
{
    static void Main()
    {
        Point p1 = new Point(5, 8);
        Point p2 = new Point(1, 2);

        Point result = p1 + p2; // Using the overloaded + operator
        Console.WriteLine(result); 
    }
}


 
/*
run:
 
(6, 10)

*/

 



answered Aug 3, 2025 by avibootz

Related questions

...