An example that uses an implicit conversion operator. : Implicit Conversion Operator : Operator Overload C# Examples


C# Examples » Operator Overload » Implicit Conversion Operator »

 

An example that uses an implicit conversion operator.









    
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;  
    }  
  
    //  An  implicit  conversion  from  TwoDimension  to  int.  
    public  static  implicit  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  =  a;  //  convert  to  int  
        Console.WriteLine("Result  of  i  =  a:  "  +  i);  
        Console.WriteLine();  
  
        i  =  a  *  2  -  b;  //  convert  to  int  
        Console.WriteLine("result  of  a  *  2  -  b:  "  +  i);  
    }  
}
    
   
  
   



Output

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


HTML code for linking to this page:

Follow Navioo On Twitter

C# Examples

 Navioo Operator Overload
» Implicit Conversion Operator