Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

C# User Defined Conversion Operator Explained

Understand C# user-defined conversion operators: syntax, implicit vs explicit choices, rules, and practical examples for custom type conversions.

~5 min readC#
#C##Conversion Operators#Type Conversion#Operator Overloading
Illustration of a C# conversion operator converting a temperature struct to a double value

User-defined conversion operators in C# let a custom type define how it converts to and from another type. You declare them as static implicit or explicit operators inside either the source type or the target type. This article explains the syntax, when to choose implicit or explicit, the restrictions C# places on these operators, and common problems you can avoid.

Declaring a Conversion Operator

A conversion operator is a static method that uses the implicit or explicit keyword, followed by the operator keyword and the target type. It must be defined inside either the source type or the target type. Consider a Temperature struct that stores Celsius internally and needs to be converted to a double.

csharp
public readonly struct Temperature { private readonly double _celsius; public Temperature(double celsius) => _celsius = celsius; public static implicit operator double(Temperature t) => t._celsius; }

This defines an implicit conversion from Temperature to double. The compiler will call this method whenever a Temperature instance is used in a context that expects a double, such as an arithmetic operation or a method argument.

To convert in the opposite direction, define a conversion from double to Temperature. Because a raw double is not necessarily a valid temperature, you might mark this conversion as explicit so callers must use a cast.

csharp
public static explicit operator Temperature(double celsius) => new Temperature(celsius);

Now you can write (Temperature)37.5 to create a temperature, but the conversion will not happen silently. The explicit keyword signals that the developer must acknowledge the conversion with a cast.

Implicit vs Explicit Conversion

The choice between implicit and explicit controls when the compiler applies the conversion automatically. An implicit conversion is applied without a cast, which makes code concise but can hide unintended conversions. An explicit conversion requires a cast, which makes the conversion point visible and signals that the operation may fail or lose data.

Use implicit when the conversion is always safe and never throws. For your own types, consider whether the conversion can lose information. If it can, mark it explicit. A conversion that throws an exception should never be implicit, because the exception would appear to originate from an unrelated line of code.

The compiler also uses implicit conversions during overload resolution. If you define an implicit conversion from your type to int, any method that accepts an int will accept your type. This can lead to surprising overload choices, especially when multiple conversions are available.

Rules and Restrictions

C# imposes several rules on user-defined conversion operators. You cannot define a conversion to or from a base class or interface; the language already provides those conversions. You also cannot define a conversion to object or from object. The conversion must involve the containing type: either the source or the target must be the type in which the operator is declared.

You cannot define both an implicit and an explicit conversion between the same two types. You must choose one. You also cannot redefine a predefined conversion that the language already provides, such as from int to long. The operator must be public and static. It cannot be virtual or abstract. The source and target types must be distinct; you cannot convert a type to itself.

These rules exist to prevent ambiguity and to avoid overriding the language's built-in conversion behavior. When you design a conversion operator, check that it does not conflict with an existing conversion path.

When to Use Implicit Conversion

Implicit conversions are convenient when the conversion is lossless and semantically obvious. A common example is a custom numeric type that wraps a decimal. If the wrapper always has a valid decimal value, an implicit conversion to decimal makes sense. The reverse conversion might need validation, so it should be explicit.

Another example is a UserId type that wraps an int. If every int is a valid user ID, an implicit conversion from int to UserId could be acceptable. But if the ID must be positive, an explicit conversion with validation is safer. The explicit conversion can throw an ArgumentOutOfRangeException when the value is invalid, and the caller will see the cast in the code.

Implicit conversions reduce boilerplate in code that works with the underlying primitive. However, they also hide the conversion point. When debugging, it may not be obvious that a conversion occurred. If the conversion has any side effects or can fail, prefer explicit.

Performance and Maintainability Considerations

Conversion operators are resolved at compile time, so they do not add runtime overhead beyond the method call itself. The method body can be as simple as a field access or as complex as a calculation. Keep the body short and free of side effects. A conversion that throws an exception or performs I/O is surprising and hard to reason about.

From a maintainability perspective, conversion operators create coupling between types. If the underlying representation changes, you must update the conversion logic. Prefer conversions that are pure functions of their input. Avoid converting to a type that is not conceptually related to the source type.

When you define a conversion, consider whether the operation could be better expressed as a named method like ToFahrenheit() or FromCelsius(). Conversion operators are appropriate when the conversion is a natural part of the type's semantics, not when it is an occasional utility operation. If the conversion is used only in one or two places, a named method is often clearer.

Common Pitfalls and Edge Cases

One common mistake is throwing an exception from an implicit conversion. Because the compiler inserts implicit conversions without visible syntax, an exception can appear to come from an unrelated line of code. Keep implicit conversions exception-free.

Another issue is ambiguity. If you define conversions that allow multiple paths between types, the compiler may reject code with an ambiguous conversion error. If you define conversions from A to B and from B to C, the compiler will not chain them automatically. You must define a direct conversion from A to C if needed.

Be aware of nullable value types, but do not assume you need separate operators for them. The compiler lifts a user-defined conversion between two non-nullable value types. For example, with the Temperature to double operator above, a Temperature? can be converted to double?; a null Temperature? produces a null double?. You do not need a second operator for the nullable form.

Also, conversion operators do not participate in inheritance. If you derive from a class that defines a conversion, the derived type does not inherit that operator. The operator is static and tied to the declaring type. This means you cannot rely on a conversion defined in a base class when working with a derived type; you must define the conversion on the derived type if needed.

Try matching browser tools

All tools

Small utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.

All C# guides

More in C#

All C# guides

The guides filed next to this one in C#, in library order.