Implicit – Explicit Conversion Operators


The explicit keyword declares a user-defined type conversion operator that must be invoked with a cast. Where as the implicit keyword is used to declare an implicit user-defined type conversion operator. Use it to enable implicit conversions between a user-defined type and another type, if the conversion is guaranteed not to cause a loss of data.

I would use a self explanatory example to describe Explicit.

using System;
namespace ConsoleApplication1
{
  class Celsius
  {
    public float c_Degrees { get; set; }
    public Celsius(float p) // ctor
    {
      this.c_Degrees = p;
    }
  }

  class Fahrenheit
  {
    public float f_Degrees { get; set; }

    public Fahrenheit(float p) // ctor
    {
      this.f_Degrees = p;
    }
    public static explicit operator Celsius(Fahrenheit fahr) // Explicit Conversion Operator
    {
      return new Celsius((5.0f / 9.0f) * (fahr.f_Degrees - 32));
    }
  }

  class Program
  {
    static void Main(string[] args)
      {
        Fahrenheit fahr = new Fahrenheit(100.0f);
        Celsius cels = (Celsius)fahr;
        Console.WriteLine("{0} Fahrenheit to {1} Celsius", fahr.f_Degrees, cels.c_Degrees);
      }
  }
}
Advertisements

Published by

Aarsh Talati

Software Developer

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s