skip to content

In a C# units-of-measure library, when should a Celsius conversion operator be implicit rather than explicit, and which declarations does the compiler reject?

level: middleimportance: should knowfreq 45%

answer

  1. implicit means silent at every call site
  2. never throws, never loses information
  3. public static, enclosing type on one side
  4. one user-defined step per conversion

basics

~20 s

Make a conversion operator implicit only when it can never throw or lose information; otherwise make it explicit so callers must cast. It must be public static, involve the enclosing type, and avoid interface, base, derived or same-type conversions.

solid answer

~50 s

The C# docs set the rule: predefined implicit conversions never throw, so a user-defined implicit conversion should not either, and one that can throw or lose information should be `explicit`. In a units library, `Celsius` from `double` validates absolute zero and can throw, and `Celsius` to `Fahrenheit` changes the unit and rounds, so both belong behind a visible cast. The declaration is `public static implicit|explicit operator Target(Source value)`, and leaving out `public` or `static` is CS0558. One side must be the enclosing type (CS0556), and conversions to or from an interface (CS0552), a base or derived class (CS0553, CS0554) or the same type (CS0555) are rejected, as is declaring both implicit and explicit for the same pair (CS0557). The conversion is chosen at compile time from static types: at most one user-defined step, so `(Fahrenheit)kelvin` through `Celsius` is CS0030, and an `object` variable gets an unboxing, not the operator.

code

csharp · 31 lines
csharp
Celsius room = 25;                                 // int -> double -> Celsius, implicitly
Fahrenheit shown = (Fahrenheit)room;               // explicit user-defined conversion
Console.WriteLine($"{shown.Degrees}");

Kelvin probe = new(300);
Fahrenheit chained = (Fahrenheit)(Celsius)probe;   // one user-defined step per cast
Console.WriteLine($"{chained.Degrees:F0}");

object fromFeed = room;
try { var bad = (Fahrenheit)fromFeed; }            // static type object: an unboxing, no operator
catch (InvalidCastException) { Console.WriteLine("InvalidCastException"); }

try { Celsius impossible = -300; }                 // an implicit conversion that throws
catch (ArgumentOutOfRangeException) { Console.WriteLine("implicit conversion threw"); }

readonly record struct Kelvin(double Degrees)
{
    public static explicit operator Celsius(Kelvin k) => new(k.Degrees - 273.15);
}
readonly record struct Celsius
{
    public double Degrees { get; }
    public Celsius(double degrees)
    {
        ArgumentOutOfRangeException.ThrowIfLessThan(degrees, -273.15);
        Degrees = degrees;
    }
    public static implicit operator Celsius(double degrees) => new(degrees);
    public static explicit operator Fahrenheit(Celsius c) => new(c.Degrees * 9 / 5 + 32);
}
readonly record struct Fahrenheit(double Degrees);

go deeper

for a junior

Recall the declaration form, public static implicit or explicit operator Target(Source value), and that explicit ones need a cast at the call site.

for a middle

Explain the never-throw, never-lose guideline for implicit conversions and the compiler's restrictions on interfaces, base types and duplicates.

for a senior

Diagnose conversions that silently do not run, such as casts from object variables or chained operators, by reasoning about static types at the call site.

for a principal

Weigh how much implicit conversion a public units API should offer, since every implicit operator becomes a silent conversion in callers' code that is hard to retract.

## Declaring a conversion operator A **user-defined conversion** lets a type take part in assignments and cast expressions as if it were built in. A units-of-measure library for a weather-station dashboard might let `Celsius room = 25;` work, and let `(Fahrenheit)room` produce a display value. Both are declared with the `operator` keyword: ```csharp public static implicit operator Celsius(double degrees) => new(degrees); public static explicit operator Fahrenheit(Celsius c) => new(c.Degrees * 9 / 5 + 32); ``` - An **implicit** conversion runs with no syntax at the call site: in an assignment, an argument or a return statement. - An **explicit** conversion runs only inside a cast expression such as `(Fahrenheit)room`. ## Implicit or explicit: the rule the docs give The C# reference states that predefined implicit conversions always succeed and never throw, that user-defined implicit conversions should behave the same way, and that a conversion that can throw or lose information should be explicit. Applied to the units library: | Conversion | Can it throw or lose data? | Declare it | |---|---|---| | `double` to `Celsius` with an absolute-zero check | throws `ArgumentOutOfRangeException` below -273.15 | explicit | | `double` to `Celsius` with no validation | no | implicit is acceptable | | `Celsius` to `Fahrenheit` | changes the unit; floating-point rounding | explicit | | `Celsius` to `double` (the raw number) | drops the unit, not the value | a judgment call; explicit keeps units visible | The guideline is a **should**, not a compiler rule: nothing stops an implicit operator from throwing. The cost is that an exception then appears on a line that contains no visible conversion, such as `Celsius impossible = -300;`, which is exactly what the code example below demonstrates. ## What the compiler rejects The compiler enforces the shape of every conversion operator, and the .NET 10 SDK reports: 1. **CS0558** when the operator is not both `public` and `static`. 2. **CS0556** when neither the source nor the target is the enclosing type; a conversion between two other types cannot be declared in a third. 3. **CS0552** for a conversion to or from an interface, since interface conversions are already reference or boxing conversions. 4. **CS0553** and **CS0554** for a conversion to or from a base or derived class, since inheritance already supplies those conversions. 5. **CS0555** for a conversion from a type to itself. 6. **CS0557** when one type declares both an implicit and an explicit conversion for the same source and target pair. ## How a conversion is chosen User-defined conversions are bound when the **calling code is compiled**, using the static types of the expressions: - A conversion may wrap **one** user-defined operator with standard conversions on either side, so `Celsius room = 25;` works as `int` to `double` (standard) and then `double` to `Celsius` (user-defined). - Two user-defined operators are never chained. With `Kelvin` to `Celsius` and `Celsius` to `Fahrenheit` declared, `(Fahrenheit)kelvin` is error CS0030; writing `(Fahrenheit)(Celsius)kelvin` makes both steps visible and compiles. The same is true when both operators are implicit. - Because the choice is made from the static type, a cast from an `object` variable never finds the operator. `(Fahrenheit)fromFeed`, where `object fromFeed` holds a `Celsius`, is compiled as an unboxing to `Fahrenheit` and throws `InvalidCastException`. ## Where conversion operators do not run - The `as` operator and the `is` type test ignore user-defined conversions; only a cast expression or an implicit conversion context invokes them. - A variable typed `object` that holds the value hides the operator, as shown above: the cast compiles as an unboxing. ## Related design points - Since C# 11 an explicit conversion can also have a **checked** form, `public static explicit operator checked int(Reading r)`, which the compiler calls inside a checked context; it requires a matching regular explicit operator (CS9025). - The code analysis rule **CA2225** asks for named alternates such as `ToFahrenheit` or `FromCelsius` beside conversion operators, for languages without operator overloading. It is not enabled by default in .NET 10. ## What a strong answer covers A good interview answer separates the **guideline** from the **compiler rules**. The guideline decides implicit versus explicit from the conversion's behaviour: whether it can fail, and whether it discards information the caller cares about, such as the unit. The compiler rules decide whether the declaration is legal at all. A strong candidate then adds the binding rule, because it explains the bugs: conversions follow the static type at the call site, apply one user-defined step, and never run through `as`, `is` or an `object` variable.

  • What is a checked explicit conversion operator, and when does the compiler call it?
    Since C# 11, `public static explicit operator checked int(Reading r)` declares the form used inside a checked context, such as `checked((int)reading)` or a project with `CheckForOverflowUnderflow`. It must be paired with a regular explicit operator for the same types, or the compiler reports CS9025. Outside a checked context the regular operator runs.
  • Why does `(Fahrenheit)kelvin` fail even though Kelvin converts to Celsius and Celsius converts to Fahrenheit?
    A C# conversion uses at most one user-defined operator, optionally surrounded by standard conversions such as `int` to `double`. Kelvin to Fahrenheit would need two user-defined steps, so the compiler reports CS0030. Writing `(Fahrenheit)(Celsius)kelvin` makes each step an explicit choice at the call site.

  • Making a conversion implicit because callers find casts noisy, even though it can throw.
  • Expecting C# to chain Kelvin to Celsius to Fahrenheit through two operators.
  • Believing a cast from an object variable will find the value's conversion operator.
  • Declaring a conversion to an interface or base class to make the type fit an API.
  • Assuming as or is will apply a user-defined conversion.