How do you define a custom implicit or explicit conversion operator between your type and another type?
Short answer
'implicit operator' lets the compiler AUTOMATICALLY convert between types without an explicit cast (used when the conversion is always safe and lossless); 'explicit operator' requires the caller to write an explicit cast, appropriate when the conversion could lose information or…
Advertisement
AModel answer
'implicit operator' lets the compiler AUTOMATICALLY convert between types without an explicit cast (used when the conversion is always safe and lossless); 'explicit operator' requires the caller to write an explicit cast, appropriate when the conversion could lose information or fail — this is exactly how int implicitly converts to double, but double requires an explicit cast down to int.
public struct Fahrenheit {
public double Degrees;
public static implicit operator Fahrenheit(double degrees) => new Fahrenheit { Degrees = degrees };
public static explicit operator double(Fahrenheit f) => f.Degrees; // requires (double)fahrenheitValue
}
Fahrenheit temp = 98.6; // implicit conversion from double
double raw = (double)temp; // explicit conversion requiredReal-world example
Allowing a domain-specific value type (like Fahrenheit or Money) to convert naturally to/from a primitive type where appropriate.
Likely follow-ups
- Why should a LOSSY or potentially-failing conversion always be marked 'explicit' rather than 'implicit'?
Related topics