Tech moves fast! Stay ahead of the curve with Techopedia!
Join nearly 200,000 subscribers who receive actionable tech insights from Techopedia.
A conversion operator, in C#, is an operator that is used to declare a conversion on a user-defined type so that an object of that type can be converted to or from another user-defined type or basic type. The two different types of user-defined conversions include implicit and explicit conversions.
In general, explicit and implicit conversion operators provide the capability to a class to be cast to the other possible data types.
An explicit conversion operator must be invoked with a cast and is used when the conversion has to be visible to the operator's users. It is used in cast expressions where the two data types are not entirely compatible and therefore require a cast operator.
An implicit conversion operator is easy to use. It does not require special syntax and it improves the code readability. It also helps a class to convert data of a data type to its compatible type without type casting. Implicit cast has to be used in situations like function member invocations and assignments, where there is no risk of data loss or the occurrence of exceptions.
An implicit conversion can be defined for a class using the keyword "implicit" along with the "operator" keyword. An explicit conversion operation can be defined for a class using the keyword "explicit" along with the "operator" keyword. Both the conversions must be defined as static.
For example, a class, RomanNumeral, can be defined with two conversion operators. An implicit conversion operator can be defined to convert from RomanNumeral class to string for displaying a number in Roman numeral form; the explicit conversion operator can be defined to perform the conversion from RomanNumeral class to integer.
Conversion of a class to object type or interface type is not allowed. The same goes for conversion from base class to a class derived from base class.
For a given class, both the explicit and implicit operators cannot be specified for conversion from the same type to another.
Care should be taken to ensure that an implicit conversion does not result in data loss or an exception. If there are valid reasons to throw exception, the conversion should be of explicit type.