Skip to main content

How to Write an Implicit Conversion Operator in C#

· 7 min read
Jagdish Kumawat
Founder @ Dewiride

An implicit conversion operator lets you write Celsius morning = 12.5; and pass a plain double wherever a Celsius is expected. C# calls your operator for you, with no cast in sight.

Microsoft's reference: A user-defined type can define a custom implicit or explicit conversion from or to another type, provided a standard conversion doesn't exist between the same two types. Implicit conversions don't require special syntax to be invoked and can occur in various situations, for example, in assignments and methods invocations. It comes with one rule of conduct: Predefined C# implicit conversions always succeed and never throw an exception. User-defined implicit conversions should behave in that way as well.

Syntax​

Syntax
public static implicit operator <TargetType>(<SourceType> <value>) => <expression>;
PartWhat it is
public staticRequired. The compiler errors guide: The C# language requires all user-defined operators to be both static and public
implicitNo cast needed. With explicit instead, callers have to write a cast, such as (Celsius)12.5
operator <TargetType>The type the value is converted to. A conversion operator's name is its return type
<SourceType> <value>The type it's converted from, and the value
<expression>Builds the <TargetType> value

Where it goes: The type that defines a conversion must be either a source type or a target type of that conversion.

The Example​

A console app called ImplicitConversion has a small Celsius struct that holds a temperature. Two implicit operators turn a double into a Celsius and a Celsius back into a double, and the code uses both without a single cast.

Prerequisites​

  • The .NET 10 SDK. dotnet --version prints a version that starts with 10.0.

Step 1: Create a Console App​

Terminal
dotnet new console -n ImplicitConversion
cd ImplicitConversion
Output
The template "Console App" was created successfully.

Processing post-creation actions...
Restoring /Users/you/source/ImplicitConversion/ImplicitConversion.csproj:
Determining projects to restore...
Restored /Users/you/source/ImplicitConversion/ImplicitConversion.csproj (in 45 ms).
Restore succeeded.

dotnet new console -n ImplicitConversion creates a folder named ImplicitConversion with a project file and a Program.cs, and cd moves into it. Everything this example uses is part of .NET, so there's no package to add. Open the folder in VS Code, or ImplicitConversion.csproj in Visual Studio.

Step 2: Write the Code​

Replace everything in Program.cs. First, numbers where a Celsius is expected:

Program.cs (double to Celsius)
// A double where a Celsius is expected: the implicit operator converts it.
Celsius morning = 12.5;
PrintTemperature(morning);
PrintTemperature(19.5);
  • Celsius morning = 12.5;: 12.5 is a double and the variable is a Celsius, so the compiler calls the operator that converts a double to a Celsius.
  • PrintTemperature(19.5): the same conversion runs for a method argument, because PrintTemperature takes a Celsius.

Then a Celsius where a double is expected:

Program.cs (Celsius to double)
// A Celsius where a double is expected: the other operator converts it back.
double degrees = morning;
Console.WriteLine($"As a double: {degrees}");

double degrees = morning; calls the other operator, which returns the temperature's Degrees.

Last, the method and the struct:

Program.cs (the struct)
static void PrintTemperature(Celsius temperature) => Console.WriteLine($"Temperature: {temperature}");

readonly struct Celsius
{
public Celsius(double degrees) => Degrees = degrees;

public double Degrees { get; }

// double to Celsius, with no cast.
public static implicit operator Celsius(double degrees) => new(degrees);

// Celsius to double, with no cast.
public static implicit operator double(Celsius temperature) => temperature.Degrees;

public override string ToString() => $"{Degrees} C";
}
  • PrintTemperature takes a Celsius and prints it. In the interpolated string, {temperature} uses its ToString(), which adds the unit, C.
  • public static implicit operator Celsius(double degrees) turns a double into a Celsius by calling the constructor.
  • public static implicit operator double(Celsius temperature) goes the other way and returns Degrees.

Step 3: Run It​

Run it in VS Code's terminal, or press Ctrl+F5 in Visual Studio:

Terminal
dotnet run
Output
Temperature: 12.5 C
Temperature: 19.5 C
As a double: 12.5

macOS-style terminal window titled Terminal — ImplicitConversion showing dotnet run printing Temperature: 12.5 C, Temperature: 19.5 C and As a double: 12.5

The code never wrote a Celsius by hand, yet 12.5 C and 19.5 C printed: the operator turned each double into a Celsius. Then morning went back into a plain double, which printed as 12.5.

The Complete File​

macOS-style code window titled Program.cs — ImplicitConversion showing a double assigned to a Celsius variable, PrintTemperature called with a Celsius and with 19.5, a Celsius assigned to a double, and a readonly struct Celsius with a Degrees property, two public static implicit operators, one from double to Celsius and one from Celsius to double, and a ToString that adds C

Program.cs
// A double where a Celsius is expected: the implicit operator converts it.
Celsius morning = 12.5;
PrintTemperature(morning);
PrintTemperature(19.5);

// A Celsius where a double is expected: the other operator converts it back.
double degrees = morning;
Console.WriteLine($"As a double: {degrees}");

static void PrintTemperature(Celsius temperature) => Console.WriteLine($"Temperature: {temperature}");

readonly struct Celsius
{
public Celsius(double degrees) => Degrees = degrees;

public double Degrees { get; }

// double to Celsius, with no cast.
public static implicit operator Celsius(double degrees) => new(degrees);

// Celsius to double, with no cast.
public static implicit operator double(Celsius temperature) => temperature.Degrees;

public override string ToString() => $"{Degrees} C";
}

Common Mistakes​

MistakeWhat happensDo this instead
Leaving out staticpublic implicit operator Celsius(double degrees) didn't build: error CS0558: User-defined operator 'Celsius.implicit operator Celsius(double)' must be declared static and publicWrite public static implicit operator
A conversion between two other typesInside Celsius, implicit operator string(double degrees) didn't build: error CS0556: User-defined conversion must convert to or from the enclosing typeConvert to or from the type that declares the operator
An implicit conversion that can failWith a constructor that rejects temperatures below -273.15, Celsius impossible = -300; threw ArgumentOutOfRangeException: degrees ('-300') must be greater than or equal to '-273.15'. from a line with no visible callMake it explicit, so callers write a cast. The reference: If a custom conversion can throw an exception or lose information, define it as an explicit conversion.
Console.WriteLine(morning)It printed 12.5, not 12.5 C: with an implicit conversion to double, the call went to Console.WriteLine(double), and ToString() never ranPrint it in an interpolated string, $"{morning}", or call morning.ToString(): both printed 12.5 C

FAQ​

Why is var morning = 12.5 a double?​

Because nothing asks for a Celsius there. var takes the type of 12.5: morning.GetType().Name printed Double, and with Celsius morning = 12.5; it printed Celsius. The conversion only runs where a Celsius is expected.

Can one conversion lead to another?​

Not two of your own in a row. With an implicit conversion from Celsius to a Fahrenheit struct, Fahrenheit hot = 12.5; didn't build: error CS0029: Cannot implicitly convert type 'double' to 'Fahrenheit'. A built-in conversion can come first, though: Celsius warm = 25; built, and $"{warm}" printed 25 C, since an int converts to a double on its own. The C# specification: A user-defined implicit conversion consists of an optional standard implicit conversion, followed by execution of a user-defined implicit conversion operator, followed by another optional standard implicit conversion.

Do is and as use the conversion?​

No. After object boxed = 12.5;, boxed is Celsius was False. The reference: The is and as operators don't consider user-defined conversions.

Conclusion​

Declare public static implicit operator in one of the two types, and C# converts for you in assignments and method calls. Keep implicit conversions for ones that can't fail or lose information, and make the rest explicit.

Additional Resources​