Home > Net >  When to use implicit and explicit operators in C#
When to use implicit and explicit operators in C#

Time:08-17

Writing implicit and explicit type conversion operators is trivial.

I can find lots of documentation about how to write them, but very little about when, or why to write them.

I've done some investigations into existing implementations; for example, BigInteger from .NET's reference source:

public struct BigInteger : IFormattable, IComparable, IComparable<BigInteger>, IEquatable<BigInteger>
{
    public static implicit operator BigInteger(Byte value)
    {
        return new BigInteger(value);
    }

    public static explicit operator Byte(BigInteger value)
    {
        return checked((byte)((int)value));
    }
}

Given the excerpt above, what is the rational for using an implicit operator when converting from Byte to BigInteger, but using an explicit operator when converting from BigInteger to Byte?

CodePudding user response:

As I mentioned in my comment, my assumption was that implicit operators should always be considered safe, whereas explicit operators may be safe but in some cases may need to be handled.

I found the following documentation on pre-defined implicit operators:

The pre-defined implicit conversions always succeed and never cause exceptions to be thrown.

Note: Properly designed user-defined implicit conversions should exhibit these characteristics as well. end note

In addition, the documentation for explicit conversions does not give the same guarantees:

The explicit conversions that are not implicit conversions are conversions that cannot be proven always to succeed, conversions that are known possibly to lose information, and conversions across domains of types sufficiently different to merit explicit notation.

This clearly backs up my assumption that implicit operators must ALWAYS be safe and never require exception handling, whereas explicit operators can and do throw exceptions, as in your example of the explicit operator that is checked.

  • Related