Library tutorials & articles
Delegates in VB.NET
- What are Delegates?
- Multicast Delegates
- Asynchronous Callbacks
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)
del.Invoke()
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.
Related articles
Related discussion
-
insert in master table and update in other table
by shahid123 (0 replies)
-
sending sms from pc
by sriraj20074 (0 replies)
-
add [DOT] to text line
by kayatri (0 replies)
-
Looping in text file
by kayatri (0 replies)
-
need help in designing a media player using vb.net/ocx object
by kensville (0 replies)
Related podcasts
-
xpert to Expert: Inside Concurrent Basic (CB)
"Concurrent Basic extends Visual Basic with stylish asynchronous concurrency constructs derived from the join calculus. Our design advances earlier MSRC work on Polyphonic C#, Comega and the Joins Library. Unlike its C# based predecessors, CB adopts a simple event-like syntax familiar to VB progr...
This thread is for discussions of Delegates in VB.NET.