Overloading Operators

In Chapter 4 you learned about operators offered by the Visual Basic grammar. Although Visual Basic does not enable creating new custom operators, it offers the possibility of overloading existing operators. In other words, you have the ability to extend existing operators with custom versions. You might wonder when and why this could be necessary. You get an answer to this question with the following code. Consider the simple structure that represents a three-dimensional coordinate:

image

Now imagine that, for any reason, you want to sum two instances of the structure using the + operator. If you try and write the following code

'Won't compile, throws an error
Dim result As ThreePoint = t1 + t2

the Visual Basic compiler throws an error saying that the + operator is not defined for the ThreePoint structure. You should begin understanding why operator overloading can be a good friend. The same situation is for other operators. In Visual Basic you overload operators using a Public Shared Operator statement within your type definition. For example, the following code overloads the + and - operators:

image

Of course this is just an example, and you might want to perform different calculations. Both overloads return a ThreePoint structure whose members have been populated with the sum and the difference between the X, Y, and Z properties, respectively, from both initial instances. When overloading operators, you need to remember that some of them require you to also overload the negation counterpart. For example, the equality = operator cannot be overloaded alone but requires the overloading of the inequality <> operator. You will be informed by the Visual Basic background compiler when an operator can’t be overloaded alone. The following code shows an overloading example of equality and inequality operators for the ThreePoint structure:

image

IntelliSense can help you understand what operators can be overloaded. For your convenience a list of operators that can be overloaded is summarized in Table 11.1.

Table 11.1 Operators That Can Be Overloaded

image

Operators Context

Overloading operators is discussed in this chapter because operators such as sum or subtraction make more sense with value types, but obviously this technique is also allowed with classes, for example for comparison operators. You can certainly overload operators within reference types, too.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.12.84.150