Partager via


Operator Overloading

One of
the new features we're adding to Visual Basic is called Operator Overloading. This feature allows the programmer to create
a class that knows what +, -, *, and other operators mean.

There are
two main components to operator overloading: consumption and declaration. (Actually, I've just described a major precept of language design. Although
they go hand-in-hand, the declaration form of a feature and the consumption
form of a feature are two intrinsically different concepts. The dichotomy
reveals itself even in .NET executables. When people talk about
"metadata", they are referring to declarations. When people talk
about intermediate language (IL) opcodes, they are
referring to consumption.)

Let's take
a look at consumption first with an example.The System.Drawing namespace contains the
types Point and Size. A new point can be
calculated by adding or subtracting a size from an already existing point. Programmatically, the + and – operators lend
themselves naturally to this calculation:

Dim
p1 As New Point(10, 10)

Dim
s1 As New Size(20, -10)

Dim
p3 As Point = p1 + s1

Dim
p4 As Point = p1 - s1

MsgBox(p3.ToString)

MsgBox(p4.ToString)

Because
Point overloads the + and - operators, this code compiles and works as
expected, outputting:

{X=30,Y=0}

{X=-10,Y=20}

How was
this done? When the compiler analyzes
the expression "p1 + s1", it discovers the type of "p1" is
Point and that Point defines Operator +. Operators are actually just functions with funny names, so the compiler
turns "p1 + s1" into a function call, equivalently written as:

Dim
p3 As Point = System.Drawing.Point.op_Addition(p1, s1)

This is the key to understanding
overloaded operators
: they are just functions. An expression like "a + b" is
really a call to the + operator with two arguments: "+(a,
b)". Because member names cannot
contain symbols like "+", the compiler uses a special name behind the
scenes: "op_Addition(a, b)". And as
functions, the compiler uses normal overload resolution rules to pick the
correct overload (in exactly the same way the compiler uses these rules to pick
the correct overload of Console.WriteLine, which at
last count had 19 overloads!).

Perhaps
you can guess what the declarations of overloaded operators look like; they're an awful
lot like functions:

Public
Shared Operator
+(ByVal
Left As Point, ByVal Right As
Size) As Point

    Return
New Point(Left.X + Right.Width, Left.Y + Right.Height)

End
Operator

Public
Shared Operator
-(ByVal
Left As Point, ByVal Right As
Size) As Point

    Return
New Point(Left.X – Right.Width, Left.Y – Right.Height)

End
Operator

The
Visual Basic compiler will allow you to overload several operators, summarized
in the table below:

+

+ (unary)

-

- (unary)

*

\

/

^

&

Like

Mod

And

Or

Xor

Not

<<

>>

= (comparison only)

<>

<

<=

>

>=

CType

IsTrue

IsFalse

CType,
IsTrue and IsFalse are
special and I'll cover those in a future entry. But quickly, you can overload conversions between types using the CType operator (instead of overloading the = assignment
operator). And IsTrue
and IsFalse are for overloading AndAlso
and OrElse which are themselves
not directly overloadable.

A few
rules greatly simplify the design and use of operator overloading: each operator declaration must be Public and
Shared, and must be declared in the same type as one of its operands. And some operators, like <= and >=,
must be pair-wise declared, i.e., a declaration of one requires an identical
declaration of the other. You'll find,
as I did, that these simple rules make understanding operator overloading much,
much easier.

More info
to follow...

Comments

  • Anonymous
    October 21, 2003
    Nice to see a VB blog. There's far too many by that C# rabble...
  • Anonymous
    October 23, 2003
    What is the form of the function declaration going to be? I assume op_blahblahblah to keep things consistent.
  • Anonymous
    October 24, 2003
    The comment has been removed
  • Anonymous
    November 02, 2003
    Operator overloading! w00t! Finally. : ) Now, if only we could get generics (I wish...)...Although I agree with Mark, I'm so glad to finally see a VB blog... the way MS carries on, you'd think VB.NET doesn't really exist. On a related note, I don't suppose we'll see the reintroduction of those lovely Bitwise AND, OR, XOR, etc. operators? I spent about twenty minutes trying to work out why bitmasking wasn't working...
  • Anonymous
    November 03, 2003
    Daniel:I'll talk about generics shortly. :)The bitwise operators still exist, just like in VB6. And, Or, Xor still do bit masking on integral types. AndAlso and OrElse were added in VB.NET for logical short-circuiting.
  • Anonymous
    December 03, 2003
    So when is this coming out!?
  • Anonymous
    December 17, 2003
    The comment has been removed
  • Anonymous
    January 03, 2004
    Question: Which version of VB is this supposed to be in? It is not in VB7 (for reasons I dont understand). Will it be in VB8? Or .Net 2004 (if such a thing exists) as an upgrade?
  • Anonymous
    January 17, 2004
    Mot: This will be included in the next version of VB. Operator Overloading wasn't included in VB7 because, unfortunately, we didn't have enough time to do it.
  • Anonymous
    January 17, 2004
    The comment has been removed
  • Anonymous
    March 02, 2004
    Hey, the only problem I have with VB.NET is that you called it VB. That's like calling PASCAL 'C'.

    I've got applications with tens of thousands of lines of VB6 code, none of which can be converted reliably to VB.net. So while Bill Gates saves a few bucks by writing half a language to replace VB, we orphaned application developers are looking at spending many millions of dollars rewriting our applications from scratch, while Mr. Gates has his attention on Sun instead of on his customers.

    My code has hundreds of interacting features, and rewriting it is not going to be any fun, particularly in a language that has taken the simplest things and made them difficult.

    Things were changed to make them more 'C'-like, which is wonderful from a religious point of view, I suppose.

    And while web services are a great concept, the overhead is horrendous, making it impractical for most systems. We are already using XML in VB6 for interprogram communication, but not as web services. Using web services for interprogram communicaiton would be like going to the phone book to look up your girlfriend's number every time you call her.

    I suppose a class-action lawsuit against MS would be futile, so I'm going to contact my Senators and Congressman instead.

  • Anonymous
    May 07, 2004
    The comment has been removed
  • Anonymous
    July 17, 2004
    My former manager, Matt Gertz, has put together a paper describing VB operator overloading in greater detail. Check it out: http://msdn.microsoft.com/vbasic/whidbey/default.aspx?pull=/library/en-us/dnvs05/html/vboperatoroverloading.asp
  • Anonymous
    July 24, 2004
    The comment has been removed