The explicit keyword is used to declare an explicit user-defined type conversion operator (CLR 6.4.4 User-defined explicit conversions).
class MyType {
public static explicit
operator MyType(int i) {
// code to convert from int to MyType
...
Unlike implicit conversion, explicit conversion operators must be invoked via a cast.
int i; MyType x = (MyType)i; // int-to-MyType requires cast
Omitting the cast results in a compile-time error.
If a conversion operation can cause exceptions or lose information, you should mark it explicit. This prevents the compiler from silently invoking the conversion operation with possibly unforeseen consequences.
The following example defines a struct, Digit
, that represents a single decimal digit. An operator is defined for conversions from byte
to Digit
, but because not all bytes can be converted to a Digit
, the conversion is explicit.
using System; struct Digit { byte value; public Digit(byte value) { if (value<0 || value>9) throw new ArgumentException(); this.value = value; } // define explicit byte-to-Digit conversion operator: public static explicit operator Digit(byte b) { Console.WriteLine("conversion occurred"); return new Digit(b); } } class Test { public static void Main() { byte b = 3; Digit d = (Digit)b; // explicit conversion } }
conversion occurred