Conversion Operator Methods
While the .Net Framework provides a plethora of classes for you to use when building applications it is not all inclusive. Part of being a programmer is adding functionality to a specific system that might not be useful to all people.
Within this application’s domain, certainly custom data types might become as important as .Net’s base types. In this case you might want to have the compiler treat your objects as such; using implicit and explicit operators.
public sealed class Currency { // Constructs a Currency from a Double public Currency(Double amt) { ... } // Constructs a Currency from a String public Currency(String amt) { ... } // Convert a Currency to a Double public Double ToDouble() { ... } // Convert a Currency to a String public override ToString() { ... } }
This works well but requires explicit calls to these functions to work. This creates a new type in your code but it isn’t as privileged as framework types. You cannot have the follow code compile, let alone run.
Currency amt1 = 5.25; // Implicit cast Currency amt2 = "$3.13"; Double x = (Double) amt1; // Explicit cast String y = (String) amt2;
Now if Currency was a base type like, for example, Int32 then you could implicitly and explicitly cast it from type to type. The Currency class, written as is, above, cannot. In order to do so you must use the operator keyword in your class.
The Currency class needs to be rewritten as follows.
public sealed class Currency { // Constructs a Currency from a Double public Currency(Double amt) { ... } // Constructs a Currency from a String public Currency(String amt) { ... } // Convert a Currency to a Double public Double ToDouble() { ... } // Convert a Currency to a String public override ToString() { ... } // Allows implicitly casting to Currency from Double public static implicit operator Currency(Double amt) { return new Currency(amt); } // Allows implicitly casting to Currency from String public static implicit operator Currency(String amt) { return new Currency(amt); } // Allows explicitly casting to Double from a Currency public static explicit operator Double(Currency c) { return c.ToDouble(); } // Allows explicitly casting to String from a Currency public static explicit operator String(Currency c) { return c.ToString(); } }
Conversion operators require that the overload methods be both public and static. The implicit keyword indicates to the compiler that an explicit case does not have to appear in code to call the conversion method. The explicit keyword indicates to the compiler that an explicit cast must to present to call the conversion method.
This allows your custom types to feel more natural within your programming environment, making them seem as though they are a part of the core .Net framework. This is especially useful within core libraries that you use repeatedly.