Delegates in VB.NET

What are Delegates?

In your Visual Basic.NET journey, you have definitely encountered a well used but little understood phenomenon called a delegate. You use them everyday, but might not know it. In this article, we will take a look at what a delegate is and how it will help you to develop better software.

A delegate can be defined as a type safe function pointer. It encapsulates the memory address of a function in your code. Whenever you create or use an event in code, you are using a delegate. When the event is thrown, the framework examines the delegate behind the event and then calls the function that the delegate points to. As we will see later, delegates can be combined to form groups of functions that can be called together.

Let's first take a quick look at how to define and invoke a delegate. First we declare our delegate in our form class:

Private Delegate Sub MyDelSub()

Then we use the delegate by simply declaring a variable of the delegate and assigning the sub or function to run when called. First the sub to be called:

Private Sub WriteToDebug()
Debug.WriteLine( "Delegate Wrote To Debug Window" )
End Sub

You will notice also that it matches our declaration of MyDelSub; it's a sub routine with no parameters. And then our test code:

Dim del As MyDelSub
del = New MyDelSub(AddressOf WriteToDebug)

When we invoke the delegate, the WriteToDebug sub is run. Visual Basic hides most of the implementation of delegates when you use events, which are based off invoking a delegate. This is the equivalent of the above delegate invoke also.

Private Event MyEvent() 'declare it in the class
'to use it, add a handler and raise the event.
AddHandler MyEvent, AddressOf WriteToDebug
RaiseEvent MyEvent()

If delegates stopped at this point, they would be useless since events are less work and do the same thing. Let's get into some of the more advanced features of delegates. We will start with multicast delegates.

You might also like...


About the author

John Spano United States

John Spano cofounder and CTO of NeoTekSystems, a Greenville, South Carolina technology consulting company. NeoTekSystems offers IT consulting, custom programming, web design and web hosting. We ...

Interested in writing for us? Find out more.


Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“If Java had true garbage collection, most programs would delete themselves upon execution.” - Robert Sewell