Operator overloads allow types to be combined and compared using operators such as "+", "-", "=", and "!=". By adding operator overloads to a type, you allow developers to use the type as though it were a built-in primitive type. Operator overloading should be done only when the meaning of the operation is intuitive for the type (for example, to support adding two instances of a type that represents a numerical value). Operator overloading should not be used to provide a syntactic shortcut for non-intuitive operations.
The following example shows the signature for the addition operation of the DateTime class.
Public Shared Function op_Addition(ByVal d As DateTime, _ ByVal t As TimeSpan _ ) As DateTime
public static DateTime op_Addition( DateTime d, TimeSpan t );
Avoid defining operator overloads, except in types that should work like primitive (built-in) types.
Consider defining operator overloads in a type that should work like a primitive type.
For example, String defines operator== and operator!=.
Do define operator overloads in structures that represent numbers (such as System.Decimal).
Do not be clever when defining operator overloads. Operator overloading is useful 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 System.DateTime object from another System.DateTime object and get a System.TimeSpan object. However, it is not appropriate to use the logical union operator to union two database queries, or to use the shift operator to write to a stream.
Do not provide operator overloads unless at least one of the operands is of the type defining the overload.
The C# compiler enforces this guideline.
Do overload operators in a symmetric fashion.
For example, if you overload the equality operator, you should also overload the inequality operator. Similarly, if you overload the less-than operator, you should also overload the greater-than operator.
Consider providing methods with friendly names corresponding to each overloaded operator.
You must comply with this guideline to be CLS-compliant. The following table contains a list of operator symbols and their corresponding alternative methods and operator names.
C# operator symbol
Name of alternative method
Name of operator
ToXxx or FromXxx
ToXxx or FromXxx
Portions Copyright 2005 Microsoft Corporation. All rights reserved.
Portions Copyright Addison-Wesley Corporation. All rights reserved.
For more information on design guidelines, see the "Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries" book by Krzysztof Cwalina and Brad Abrams, published by Addison-Wesley, 2005.