Summary

  • You can overload operators in much the same way that you would overload methods.

  • To overload an operator, use the static keyword with the operator keyword, and the name of the operator you’re overloading.

  • It is good programming practice to use operator overloading sparingly and to be sure that the meaning of the overload is obvious and intuitive.

  • When you overload the equals (==) operator, you should also override the Equals() method for compatibility with other .NET languages.

  • If you overload the == operator, you must also overload the != operator. Similarly, the < and > operators are paired, as are the <= and >= operators.

  • You can also overload conversion operators to allow one type to be implicitly or explicitly cast to another type. When doing so, you must use the keyword implicit when the conversion is guaranteed to succeed without loss of information, and explicit when there is a risk that information might be lost.

Now you know how to overload constructors, regular class methods, and even operators. That’s a lot of overloading going on, but it’s all with good reason—to make your user-defined classes flexible and extensible. In the next chapter, we’ll look at yet another method of extension: interfaces. Interfaces let you dictate the methods that a class will have, without using inheritance. It’s complicated, but powerful, as you’ll see.

Get Learning C# 3.0 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.