This keyword can be applied to type conversion operators of a class.
Normally when you define a type conversion operator the compiler will implicitly
use the operator, when needed, to convert from type A to type B. In a few
cases the conversion might be important/expensive enough that you do not want
the compiler to use the operator implicitly. Applying the explicit
keyword prevents the compiler from using the operator unless you explicitly cast
the value first. In the following example we have defined a Letter
class that holds only letters. It makes sense to allow conversion to and
from characters. Therefore we define a type conversion operator like so.
class Letter
{
public Letter ( char value )
{
Value = value;
}
public static implicit operator Letter(char value)
{
return new Letter(value);
}
public char Value
{
get { return m_Value; }
set
{
if (!Char.IsLetter(value))
throw new ArgumentException("Not a letter.", "value");
m_Value = value;
}
}
private char m_Value;
}
//Usage
static void Main ( )
{
Letter letter = new Letter('B');
letter = 'a';
}
However it can be confusing when an implicit type conversion is used and it
throws an exception (as it would here if the character was not a letter).
Therefore it is often better to make the conversion explicit, but allowable, via
the explicit keyword like so. Now the user must put an explicit
typecast in their code but if something goes wrong it is far more obvious what
the problem might be.
public static explicit operator Letter(char value)
{
return new Letter(value);
}
//Usage
static void Main ( )
{
Letter letter = new Letter('B');
letter = (Letter)'a';
}