Converting User Defined Types via implicit operator - CSharp Custom Type

CSharp examples for Custom Type:Operator Overloading

Description

Converting User Defined Types via implicit operator

Demo Code

using System;/*www. j  a  v  a 2s.  c o  m*/
class MyTimer
{
   private uint totalSeconds;
   public MyTimer(uint initialTotalSeconds)
   {
      totalSeconds = initialTotalSeconds;
   }
   public uint TotalSeconds
   {
      get
      {
         return totalSeconds;
      }
   }
   public static implicit operator BliposTimeSpan(MyTimer convertFrom)
   {
      BliposTimeSpan newBliposTimeSpan = new BliposTimeSpan(convertFrom.TotalSeconds);
      Console.WriteLine("Converting from MyTimer to BliposTimeSpan");
      return newBliposTimeSpan;
   }
}
class BliposTimeSpan
{
   private uint totalSeconds;
   public BliposTimeSpan(uint initialTotalSeconds)
   {
      totalSeconds = initialTotalSeconds;
   }
   public void PrintTimeSpan()
   {
      Console.WriteLine("Blipos time span: {0} seconds", totalSeconds);
   }
}
class ExplicitConversionTester
{
   public static void Main()
   {
      MyTimer myTimeSpan = new MyTimer(200);
      BliposTimeSpan alienTimeSpan;
      alienTimeSpan = myTimeSpan;
      alienTimeSpan.PrintTimeSpan();
   }
}

Result


Related Tutorials