Mega Code Archive

 
Categories / C# Tutorial / Operator
 

Operators ++

using System;   class Class1   {     [STAThread]     static void Main(string[] args)     {       MyCar car = 5;             for( int i = 0; i < 20; ++i )             {                 car++;                 Console.WriteLine( "{0}", car.GetSpeed());             }     }   }   public class MyCar   {         private static int speed = 2;         private const int maxSpeed = 200;                  public bool ChangeSpeed(int newSpeed)         {             if( newSpeed > maxSpeed )                 return false;             speed = newSpeed;             return true;         }         public static MyCar operator ++( MyCar car )         {             car.ChangeSpeed(++speed);             return car;         }         public static implicit operator MyCar( int from )         {             MyCar car = new MyCar();             car.ChangeSpeed( from );             return car;         }         public int GetSpeed()         {             return speed;         }   }