Skip to Main Content
Professional Visual Studio® 2008
book

Professional Visual Studio® 2008

by Nick Randolph, David Gardner
July 2008
Intermediate to advanced content levelIntermediate to advanced
1026 pages
27h 59m
English
Wrox
Content preview from Professional Visual Studio® 2008

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Professional Visual Studio® 2010

Professional Visual Studio® 2010

Nick Randolph, David Gardner, Michael Minutillo, Chris Anderson

Publisher Resources

ISBN: 9780470229880Purchase book