11.4. Operator Overloading

Both VB.NET and C# now support operator overloading, which means that you can define the behavior for standard operators such as +, −, /, and *. You can also define type conversion operators that control how casting is handled between different types.

11.4.1. Operators

The syntax for operator overloading is very similar to a static method except that it includes the Operator keyword, as shown in the following example:

C#

public class OperatorBaseClass{
    private int m_value;

    public static OperatorBaseClass operator +(OperatorBaseClass op1 ,
                                               OperatorBaseClass op2 )
    {
        OperatorBaseClass obc =new OperatorBaseClass();
        obc.m_value = op1.m_value + op2.m_value;
        return obc;
    }
}

VB.NET

Public Class OperatorBaseClass
    Private m_value As Integer

    Public Shared Operator +(ByVal op1 As OperatorBaseClass, _
                             ByVal op2 As OperatorBaseClass) As OperatorBaseClass
        Dim obc As New OperatorBaseClass
        obc.m_value = op1.m_value + op2.m_value
        Return obc
    End Operator
End Class

In both languages, a binary operator overload requires two parameters and a return value. The first value, op1, appears to the left of the operator, with the second on the right side. Clearly, the return value is substituted into the equation in place of all three input symbols. Although it makes more sense to make both input parameters and the return value the same type, this is not necessarily the case, and this syntax can be used to define the effect of the operator on any pair of types. The one condition ...

Get Professional Visual Studio® 2008 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.