In C#, we can overload the implicit conversion operator like this (example from MSDN):
struct Digit
{
/* ... */
public static implicit operator byte(Digit d) // implicit digit to byte conversion operator
{
/* ... */
}
}
Thus, we can have a type, a custom value type, magically converting itself to another (unrelated) type, leaving the audience in bewilderment (until they peer into the backstage and see the implicit conversion operator, that is).
I don't like leaving anyone who reads my code in bewilderment. I don't think many people do.
The question is, what are the use-cases of the implicit type conversion operator which won't render my code much more difficult to understand?
Best Answer
I would only recommend implicit conversions between types that roughly represent the same values in different ways. For instance:
RGB
,HSL
,HSV
andCMYK
.Meter
vsInch
).However, there are some strong guidelines that indicate when it is not appropriate to define an implicit conversion:
InvalidCast
) exception, then it shouldn't be implicit.O(1)
operation, then it shouldn't be implicit.Now say your conversion operator
f: T1 -> T2
doesn't violate any of the rules above, then the following behavior strongly indicates that the conversion can be implicit:a == b
thenf(a) == f(b)
.a != b
thenf(a) != f(b)
.a.ToString() == b.ToString()
thenf(a).ToString() == f(b).ToString()
.T1
andT2
.