Sunday, November 2, 2008

Operator Overloading

1. Define operators on value types that are logical built-in language types, such as the System.Decimal structure.
2. Provide operator-overloading methods only in the class in which the methods are defined.
3. Use the names and signature conventions described in the Common Language Specification (CLS).
4. Use operator overloading in cases where it is immediately obvious what the result of the operation will be. For example, it makes sense to be able to subtract one Time value from another Time value and get a TimeSpan. However, it is not appropriate to use the or operator to create the union of two database queries, or to use shift to write to a stream.
5. Overload operators in a symmetric manner. For example, if you overload the equality operator (==), you should also overload the not equal operator (!=).
6. Provide alternate signatures. Most languages do not support operator overloading. For this reason, always include a secondary method with an appropriate domain-specific name that has the equivalent functionality. It is a Common Language Specification (CLS) requirement to provide this secondary method. The following example is CLS-compliant



C#
class Time
{
TimeSpan operator -(Time t1, Time t2) { }
TimeSpan Difference(Time t1, Time t2) { }
}
The following table contains a list of operator symbols and the corresponding alternative methods and operator names.

No comments: