Use an explicit conversion. : Explicit Conversion 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 binary +. 
  public static TwoDimension operator +(TwoDimension op1, TwoDimension op2) 
  { 
    TwoDimension result = new TwoDimension(); 
 
    result.x = op1.x + op2.x;  
    result.y = op1.y + op2.y;  
 
    return result; 
  } 
 
  // This is now explicit. 
  public static explicit operator int(TwoDimension op1) 
  { 
    return op1.x * op1.y; 
  } 
   
  // 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(); 
    int i; 
 
    Console.Write("Here is a: "); 
    a.show(); 
    Console.WriteLine(); 
    Console.Write("Here is b: "); 
    b.show(); 
    Console.WriteLine(); 
 
    c = a + b; // add a and b together 
    Console.Write("Result of a + b: "); 
    c.show(); 
    Console.WriteLine(); 
 
    i = (int) a; // explicitly convert to int -- cast required 
    Console.WriteLine("Result of i = a: " + i); 
    Console.WriteLine(); 
 
    i = (int)a * 2 - (int)b; // casts required 
    Console.WriteLine("result of a * 2 - b: " + i); 
 
  } 
}
Here is a: 1, 2

Here is b: 10, 10

Result of a + b: 11, 12

Result of i = a: 2

result of a * 2 - b: -96








8.5.Explicit Conversion Operator
8.5.1.Use an explicit conversion.