Operator Overload Example (Overloaded)

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 static Box operator +(Box box1, int num)
  {
    int h = box1.Height + num;
    int w = box1.Width + num;
    Box result = new Box(h, w);
    return result;
  }
  public static Box operator +(int num, Box box1)
  {
    return box1 + num;
  }
}

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 + 10;
	Box b5 = 10 + b1;
	
	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);
	Console.WriteLine("Box b5: Height: {0}, Width: {1}", b5.Height, b5.Width);
  }
}
;