O'Reilly logo

Visual Basic 2012 Programmer's Reference by Rod Stephens

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

RELAXED DELEGATES

If you assign a variable to the value in a variable of a different type, Visual Basic automatically converts the value into the correct type under some circumstances. If you set a Single variable equal to an Integer variable, Visual Basic automatically converts the Integer into a Single.

If Option Strict is off, you can also do the reverse: If you assign an Integer variable equal to a Single variable, Visual Basic converts the Single into an Integer (if it can).

In a similar manner, relaxed delegates let Visual Basic convert method parameters from one data type to another under certain circumstances. If the code invokes a subroutine by using a delegate, Visual Basic tries to convert parameters when it can. Probably the easiest way to understand how this works is to consider an example.

The following code declares a delegate type named TestDelegate. Methods that match this delegate should be subroutines that take a Control as a parameter.

' Declare the delegate type.
Private Delegate Sub TestDelegate(ctl As Control)

The following code defines three subroutines that take parameters of different types. The first takes an Object as a parameter, the second takes a TextBox, and the third takes no parameters. Note that the first subroutine cannot work if Option Strict is on. Option Strict disallows late binding, so the code cannot use a Text property provided by a generic Object.

' A more general parameter type. Private Sub Test1(obj As Object) obj.Text = "Test1" ' Needs ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required