User-Defined Conversions
Add implicit and explicit conversion operators.
User-Defined Conversions
C# lets a type define how it converts to or from another type using the implicit and explicit operators. Implicit conversions happen automatically; explicit ones require a cast.
An Implicit Conversion
Use implicit operator when a conversion is always safe and lossless. The compiler applies it automatically wherever the target type is expected.
using System;
public struct Celsius
{
public double Degrees;
public Celsius(double d) { Degrees = d; }
// Always safe: a Celsius is just a number
public static implicit operator double(Celsius c) => c.Degrees;
}
public class Program
{
public static void Main()
{
Celsius temp = new Celsius(21.5);
double d = temp; // implicit, no cast needed
Console.WriteLine(d);
}
}