Convenience?
More or less, yes. Consider the case for when you’ve got a number-like object (say, a Complex
) on which you do calculations. Clearly, writing code such as:
Complex result = c1 * new Complex(2) + new Complex(32);
is very annoying and hard to read. Implicit conversions help here (an alternative would be operator overloads in this example, but that would lead to lots of similar overloads).
Is there a guideline for this?
Provide as few implicit conversions as possible, since they may hide problems. Implicit conversion reduce explicitness by the same amount by which they increase terseness. Sometimes this is good, but sometimes not.
I find it best to restrict implicit conversions to very similar types, such as the number-like objects in my example above: an int
essentially is-a Complex
(from a mathematical standpoint; even if it’s not modelled via inheritance), hence an implicit conversion makes sense.
In VB, an implicit conversion is called “Widening
” (as opposed to Narrowing
, which is explicit
) and this describes it well: no information is lost in the course of the conversion.
Furthermore, an operator is essentially a builder function, and has (some of) the usual advantages of a builder function over a constructor: namely, it can re-use cached values instead of always creating new instances.
Consider my Complex
example. We may want to cache values for often-used Complex numbers:
Class Complex {
// Rest of implementation.
private static Complex[] cache = new[] {
new Complex(-1), new Complex(0), new Complex(1) };
public implicit operator Complex(int value) {
if (value >= -1 && value <= 1)
return cache[value];
else
return new Complex(value);
}
}
Of course, whether this micro-optimization is effective is another question.