Overload C# Operators
Extend and customize C# to make your apps easier to read and maintain.
October 30, 2009
SharpShooter
Languages: C#
Technologies: Overloading| Operator Overloading
OverloadC# Operators
Extendand customize C# to make your apps easier to read and maintain.
By MikeAmundsen
C# hasmany great features that make it a powerful and fun language. One of thosefeatures is the ability to redefine the functionality and meaning of one ormore methods, including the language's built-in methods. This is calledoverloading. The ability to overload methods in C# gives you the power todesign systems that have their own self-consistent syntax and logic.Overloading also allows you to extend the language in ways that were notinitially conceived by the folks who implemented the C# language on the .NETplatform. In short, overloading is a valuable tool for extending andcustomizing the C# language for your own needs.
You canapply overloading to many situations. In this article, I'll focus on how C#enables you to overload reserved keywords in the language, such as the logicaloperators (==, !=, <, and >) and thearithmetic operators (+, -, *, /, %). You'lllearn how you can redefine the meaning and behavior of these key languageoperators to help make your own programs more self-consistent and easier toread and maintain over time.
A Simple Overloading Example: ToString
Beforegetting into the details of overloading relational and arithmetic operators, itwould be good to start with a simple overloading example: overloading the ToStringmethod. The ToString method is a base-class method inherited by all typesand classes defined in C#. It's the method used to come up with a stringrepresentation of the type or class with which you are working.
Forexample, this code uses the built-in ToString method to output the valueof an integer:
Int x = 13;
System.Console.WriteLine(x.ToString());
Becauseall classes and types inherit this method, it's easy for you to call it on anyclass or type you create. However, if you have created a custom type notpreviously defined in C#, the ToString method may not know how to outputthe string properly. FIGURE 1 shows a simple custom type named Point,which holds two values, x and y.
// compile string:
// csc /t:library/out:Amundsen.SharpShooter.Overloading.Point.dllAmundsen.SharpShooter.Overloading.Point.cs
using System;
namespace Amundsen.SharpShooter.Overloading {