#399 – Overloading Unary Operators
August 29, 2011 Leave a comment
You can overload any of the following unary operators: +, -, !, ~, ++, –, true, false. A unary operator is an operator that can be applied to a single operand.
Overloading the negation (!) operator allows us to negate an instance of a class.
Dog kirby = new Dog("Kirby", 13); Dog antiKirby = !kirby;
To overload the operator, we define a new method in our class that takes an instance of a Dog and “negates” it, returning a new instance.
public static Dog operator !(Dog d1) { string notName = new string(d1.Name.Reverse().ToArray()); return new Dog(notName, -1 * d1.Age); }
Below is an example of overloading the increment (++) operator. (We really ought to overload the decrement operator as well).
Dog olderKirby = kirby++;
public static Dog operator ++(Dog d1) { return new Dog(d1.Name, d1.Age++); }