Normally, when converting between types, you might need to use explicit casting. However, if the conversion is guaranteed to be safe (no data loss or runtime exceptions), you can define an implicit conversion. Once defined, the compiler automatically applies it wherever appropriate.
A Practical Example
Let’s create a simple Metre class that internally stores a distance value as a double. We want conversion from Metre to double.
class Metre
{
public double Value { get; }
public Metre(double value)
{
Value = value;
}
}
Two Ways to Define an Implicit Operator
In C#, you can define an implicit operator in two syntactic styles: the modern expression-bodied form and the traditional block-bodied form. Both work the same way; it’s just a matter of readability and coding style.
class Metre
{
public double Value { get; }
public Metre(double value)
{
Value = value;
}
// Expression-bodied (short, single-line)
public static implicit operator double(Metre metre) => metre.Value;
// Block-bodied (classic, multi-line)
public static implicit operator double(Metre metre)
{
return metre.Value;
}
}
double → The target type.
Metre metre → the source type.
metre.Value → the actual conversion logic: it pulls out the double value stored in the Metre object.
When Does a User-Defined Implicit Operator Run?
During Assignment
When you assign an object to a variable of the target type
Metre m = new Metre(5.0);
double d = m; //implicit operator automatically converts m to double
2.In Return Statements
When returning the object from a method with the target type
Metre m = new Metre(4.0);
double GetValue()
{
return m; //implicit operator automatically converts m to double
}
3.As a Method Argument
When passing the object as a parameter to a method expecting the target type
void PrintValue(double value)
{
Console.WriteLine(value);
}
Metre m = new Metre(7.0);
PrintValue(m); //implicit operator automatically converts m to double
4.In Expressions
When used in mathematical or other operations:
Metre m = new Metre(3.0);
double result = m + 2.0; //implicit operator automatically converts m to double
Top comments (0)