Explicit Conversion via explicit operator - CSharp Custom Type

CSharp examples for Custom Type:Operator Overloading

Description

Explicit Conversion via explicit operator

Demo Code

using System;//from  www . jav  a  2  s  .  c  o m
class TimeSpan
{
   private uint totalSeconds;
   public TimeSpan(uint initialTotalSeconds)
   {
      totalSeconds = initialTotalSeconds;
   }
   public uint TotalSeconds
   {
      get
      {
         return totalSeconds;
      }
   }
   public static explicit operator ushort(TimeSpan convertFrom)
   {
      Console.WriteLine("Converting from TimeSpan to ushort");
      return (ushort)convertFrom.TotalSeconds;
   }
}
class ExplicitConversionTester
{
   public static void Main()
   {
      ushort simpleTimeSeconds;
      TimeSpan myTime = new TimeSpan(130);
      simpleTimeSeconds = (ushort) myTime;
      Console.WriteLine("Value of simpleTimeSeconds: {0}", simpleTimeSeconds);
   }
}

Result


Related Tutorials