It is generally considered a bad idea to use implicit operators, because they are, after all, implicit and work behind your back. Debugging code littered with operator overloads is a nightmare. However, with something like this:
public class Complex
{
public int Real { get; set; }
public int Imaginary { get; set; }
public static implicit operator Complex(int value)
{
Complex x = new Complex();
x.Real = value;
return x;
}
}
you can use:
Complex complex = 10;
or you can overload operator +
public static Complex operator +(Complex cmp, int value)
{
Complex x = new Complex();
x.Real = cmp.Real + value;
x.Imaginary = cmp.Imaginary;
return x;
}
and use code like
complex +=5;
Sweko source
share