Export (0) Print
Expand All

explicit

The explicit keyword is used to declare an explicit user-defined type conversion operator (6.4.4 User-defined explicit conversions). For example:

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.

Example

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.

// cs_keyword_explicit.cs
using System;
struct Digit
{
   byte value;
   public Digit(byte value) 
   {
      if (value>9) throw new ArgumentException();
      this.value = value;
   }

   // define explicit byte-to-Digit conversion operator:
   public static explicit operator Digit(byte b) 
   {
      Digit d = new Digit(b);    
      Console.WriteLine("conversion occurred");
      return d;
   }
}

class Test 
{
   public static void Main() 
   {
     try 
      {
      byte b = 3;
      Digit d = (Digit)b; // explicit conversion
      }

      catch (Exception e)
      {
         Console.WriteLine("{0} Exception caught.", e);
      }
   }
}

Output

conversion occurred

See Also

C# Keywords | implicit | operator | User-Defined Conversions Tutorial

Show:
© 2014 Microsoft