This documentation is archived and is not being maintained.


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

class MyType 
   public static implicit operator int(MyType m) 
      // code to convert from MyType to int

Implicit conversion operators can be called implicitly, without being specified by explicit casts in the source code.

MyType x;
int i = x; // implicitly call MyType's MyType-to-int conversion operator

By eliminating unnecessary casts, implicit conversions can improve source code readability. However, because implicit conversions can occur without the programmer's specifying them, care must be taken to prevent unpleasant surprises. In general, implicit conversion operators should never throw exceptions and never lose information so that they can be used safely without the programmer's awareness. If a conversion operator cannot meet those criteria, it should be marked explicit.


The following example defines a struct, Digit, that represents a single decimal digit. An operator is defined for conversions from Digit to byte, and because any Digit can be converted to a byte, the conversion is implicit.

// cs_keyword_implicit.cs
using System;
struct Digit
   byte value;

   public Digit(byte value) 
      if (value > 9) throw new ArgumentException();
      this.value = value;

   // define implicit Digit-to-byte conversion operator:
   public static implicit operator byte(Digit d) 
      Console.WriteLine( "conversion occurred" );
      return d.value;

class Test 
   public static void Main() 
      Digit d = new Digit(3);

      // implicit (no cast) conversion from Digit to byte
      byte b = d;   


conversion occurred

See Also

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