Operator Overload Example (binary)

CSharp · Console

/Program.cs

using System;
					
public class Box
{
  public int Height { get; set; }
  public int Width { get; set; }
  
  public Box(int h, int w)
  {
    Height = h;
    Width = w;
  }
	
  public static Box operator +(Box box1, Box box2)
  {
    int h = box1.Height + box2.Height;
    int w = box1.Width + box2.Width;
    Box result = new Box(h, w);
    return result;
  }
}

public class Program
{
  public static void Main()
  {
    Box b1 = new Box(14, 3);
    Box b2 = new Box(5, 7);
	Box b3 = b1 + b2;
	Box b4 = b1 + b2 + b3;
	
	Console.WriteLine("Box b1: Height: {0}, Width: {1}", b1.Height, b1.Width);
	Console.WriteLine("Box b2: Height: {0}, Width: {1}", b2.Height, b2.Width);
    Console.WriteLine("Box b3: Height: {0}, Width: {1}", b3.Height, b3.Width);
	Console.WriteLine("Box b4: Height: {0}, Width: {1}", b4.Height, b4.Width);
  }
}
;