Overload true and false for TwoDimension. : True false operator « 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 true.   
  public static bool operator true(TwoDimension op) { 
    if((op.x != 0) || (op.y != 0)) 
      return true; // at least one coordinate is non-zero 
    else 
      return false; 
  }   
 
  // Overload false. 
  public static bool operator false(TwoDimension op) { 
    if((op.x == 0) && (op.y == 0)) 
      return true; // all coordinates are zero 
    else 
      return false; 
  }   
 
  // Overload unary --.  
  public static TwoDimension operator --(TwoDimension op)  
  {  
    // for ++, modify argument  
    op.x--;  
    op.y--;   
  
    return op;  
  }  
 
  // Show X, Y, Z coordinates.   
  public void show()   
  {   
    Console.WriteLine(x + ", " + y);   
  }   
}   
   
class MainClass {   
  public static void Main() {   
    TwoDimension a = new TwoDimension(5, 6);   
    TwoDimension b = new TwoDimension(10, 10);   
    TwoDimension c = new TwoDimension(0, 0);   
   
    Console.Write("Here is a: ");   
    a.show();   
    Console.Write("Here is b: ");   
    b.show();   
    Console.Write("Here is c: ");   
    c.show();   
    Console.WriteLine();   
   
    if(a) 
       Console.WriteLine("a is true."); 
    else 
       Console.WriteLine("a is false."); 
 
    if(b) 
       Console.WriteLine("b is true."); 
    else 
       Console.WriteLine("b is false."); 
 
    if(c) 
       Console.WriteLine("c is true."); 
    else 
       Console.WriteLine("c is false."); 
 
    Console.WriteLine(); 
 
    Console.WriteLine("Control a loop using a TwoDimension object."); 
    do { 
      b.show(); 
      b--; 
    } while(b); 
 
  }   
}
Here is a: 5, 6
Here is b: 10, 10
Here is c: 0, 0

a is true.
b is true.
c is false.

Control a loop using a TwoDimension object.
10, 10
9, 9
8, 8
7, 7
6, 6
5, 5
4, 4
3, 3
2, 2
1, 1








8.13.True false operator
8.13.1.true/false operator for Complex
8.13.2.Overload true and false for TwoDimension.
8.13.3.true and false operator