Overload binary + for object + int : object plus int « Operator Overload « C# / CSharp Tutorial






using System; 
 
class TwoDimension { 
  int x, y;
 
  public TwoDimension() { 
     x = y = 0; 
  } 
  public TwoDimension(int i, int j) { 
     x = i; 
     y = j; 
  } 
 
  // Overload binary + for object + int. 
  public static TwoDimension operator +(TwoDimension op1, int op2) 
  { 
    TwoDimension result = new TwoDimension(); 
 
    result.x = op1.x + op2; 
    result.y = op1.y + op2; 
 
    return result; 
  } 
 
  // Show X, Y 
  public void show() 
  { 
    Console.WriteLine(x + ", " + y); 
  } 
} 
 
class MainClass { 
  public static void Main() { 
    TwoDimension a = new TwoDimension(1, 2); 
    TwoDimension b = new TwoDimension(10, 10); 
    TwoDimension c = new TwoDimension(); 
 
    Console.Write("Here is a: "); 
    a.show(); 
    Console.WriteLine(); 
    Console.Write("Here is b: "); 
    b.show(); 
    Console.WriteLine(); 
 
    c = b + 10; // object + int 
    Console.Write("Result of b + 10: "); 
    c.show(); 
  } 
}
Here is a: 1, 2

Here is b: 10, 10

Result of b + 10: 20, 20








8.8.object plus int
8.8.1.Overload binary + for object + int