OPERATOR OVERLOADING

Visual Basic defines operators for expressions that use standard data types such as Integers and Boolean values. It defines a few operators such as Is and IsNot for objects, but operators such as * and Mod don’t make sense for objects in general.

Nevertheless, you can also define those operators for your structures and classes, if you like, by using the Operator statement. This is a more advanced topic, so if you’re new to Visual Basic, you may want to skip this section and come back to it later, perhaps after you have read Chapter 23, “Classes and Structures.”

The general syntax for operator overloading is:

[ <attributes> ] Public [ Overloads ] Shared [ Shadows ] _
[ Widening | Narrowing ] Operator symbol ( operands ) As type
    ...
End Operator
 

The parts of this declaration are:

  • attributes — Attributes for the operator.
  • Public — All operators must be Public and Shared.
  • Overloads — You can use this only if the operator takes two parameters that are from a base class and a derived class as its two operators. In that case, it means the operator overrides the operator defined in the base class.
  • Shared — All operators must be Public and Shared.
  • Shadows — The operator replaces a similar operator defined in the base class.
  • Widening — Indicates that the operator defines a widening conversion that always succeeds at run time. For example, an Integer always fits in a Single, so storing an Integer in a Single is a widening operation. This operator must catch and handle ...

Get Visual Basic 2012 Programmer's Reference 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.