Delegates in Visual Basic .NET

You are currently viewing Delegates in Visual Basic .NET

A delegate in Visual Basic.NET is defined as a type safe function pointer. It holds the memory address of a function or procedure in the code and can be used to invoke the function. As a Visual Basic developer, we used delegates on daily basis without even knowing that we are using them. Event handling in .NET is also based on the concept of delegates and .NET Framework automatically handles delegates behind the scenes when we handle events in the program.

In this tutorial I will show you how you can use delegates in Visual Basic.NET and how they can invoke methods after getting the reference of methods in memory.

First step to implement delegates in Visual Basic.NET is to declare one delegate in your code as shown below

Public Delegate Sub MyDelegate()

This is important to keep in mind that the above delegate declaration also determines the type of sub procedures this delegate can invoke. If your delegate MyDelegate() does not have any parameter then it can only invoke those sub procedures that are matching with the signature of delegate.  It cannot invoke procedures that are accepting parameters. 

Next step is to create sub procedure which you want to invoke using delegate. 

Public Sub WriteSomething()
 Debug.WriteLine(“Debug Output from Delegate Program”)
End Sub

Now you are ready to create Delegate type variable and simply pass the address of procedure WriteSomething to this variable using AddressOf in Visual Basic.NET.

Dim caller As MyDelegate
caller = New MyDelegate(AddressOf WriteSomething)

Last step is to invoke the procedure or function by using delegate variable.


When you will call invoke method using delegate type variable it will automatically call procedure it is pointing in memory in this case WriteSomething.

READ ALSO:  Implicitly Typed Local Variables in C#

Leave a Reply