Operators

This section describes what is operators, which are special methods that can be invoked in a syntax similar to arithmetic and comparison operations.

Operators are special methods in a class, which will allow objects of this class to invoke those methods in a syntax similar to the syntax of expression. The following program shows a simple currency class with some operators defined:

```// Currency.cs

using System;
class Currency {
private long v;
public Currency(long value) {
v = value*100;
}
public Currency(double value) {
// value is rounded down after two decimal digits
v = (long)(value*100.0);
}
public static implicit operator double(Currency a) {
return a.v/100.0;
}
public static implicit operator Currency(double a) {
return new Currency(a);
}
public static Currency operator+(Currency a, Currency b) {
Currency c = new Currency(0);
c.v = a.v+b.v;
return c;
}
public static bool operator==(Currency a, Currency b) {
return a.v == b.v;
}
public static bool operator!=(Currency a, Currency b) {
return a.v != b.v;
}
public override string ToString() {
if (v%100==0) return (v/100).ToString()+".00\$";
else return (v/100).ToString()+"."+(v%100).ToString()+"\$";
}
public static void Main() {
Currency a = new Currency(100); // constructor
Currency b = 100.125; // conversion operator
Currency c = b + b; // + operator
Currency d = 100.1249;
Console.WriteLine("a = {0}.",a); // overrided ToString()
Console.WriteLine("b = {0}.",b);
Console.WriteLine("c = {0}.",c);
Console.WriteLine("b==d = {0}.",b==d); // == operator
}
}
```

Output:

```a = 100.00\$.
b = 100.12\$.
c = 200.24\$.
b==d = True.
```

Last update: 2015.