To understand type Safe Pointer, you need to understand call back function used in C++. Call back function is generally implemented in Business Tier in 3-tier architecture. Once business logic is implemented, it requires memory address of the function or method to use it. This memory address does not have any information of Method signature, so it can be called as it is not Type Safe.
But Delegates has the feature of callback in Safe way, as it take cares of signature information.
How to define delegate,
Public Delegate Sub MakeDelegate (ByVal EmployeeID As String)
We are declaring public delegate, so it can be accessed from anywhere in the application.
Here we are going to define a Employee class which uses the delegates and method.
Public Class Employee
Public FirstName As String
Public LastName As String
Public Sub ValidEmployee (ByVal objDelegate As MakeDelegate, _
ByVal EmployeeID As String)
If EmployeeID.StartsWith ("MKT") Then
objDelegate.Invoke(EmployeeID)
End If
End Sub
End Class
The method ValidEmployee is going to accept the EmployeeID and a Delegate Object of type "MakeDelegate" as the parameters and validate whether it is a Starting with E1 and invoke the Delegate Object accordingly.Dim objEmployee As Employee = New Employee()
Dim objDelegate As MakeDelegate
objDelegate = AddressOf NotifyEmployee
objEmployee .FirstName = txtFirstName.Text
objEmployee.LastName = txtLastName.Text
objEmployee.ValidateEmployee(objDelegate, txtEmployeeID.Text)
We assign the local procedure "NotifyEmployee", which is declared and defined inside the Windows Form Class to the Delegate Object.
Private Sub NotifyEmployee(ByVal EmployeeID As String)
MsgBox("This Employee is from Marketing Department") End Sub
Once we assign the instance of the Delegate, we must provide the address of a method implementation with a matching method signature.
No comments:
Post a Comment