Posted by: Sourav | October 15, 2016

Anonymous Method Example in Visual Basic,VB Teacher Sourav,Kolkata 09748184075


Imports System.Collections.Generic
Module Module1

Public Sub Main()
Dim listEmployees As New List(Of Employee)() From { _
New Employee() With { _
.ID = 101, _
.Name = “Mark” _
}, _
New Employee() With { _
.ID = 102, _
.Name = “John” _
}, _
New Employee() With { _
.ID = 103, _
.Name = “Mary” _
} _
}

‘ Step 2: Create an instance of Predicate<Employee>
‘ delegate and pass the method name as an argument
‘ to the delegate constructor
Dim predicateEmployee As Predicate(Of Employee) = New Predicate(Of Employee)(AddressOf FindEmployee)

‘ Step 3: Now pass the delegate instance as
‘ the argument for Find() method
Dim employee As Employee = listEmployees.Find(Function(x) predicateEmployee(x))
Console.WriteLine(“ID = {0}, Name {1}”, employee.ID, employee.Name)

‘ Anonymous method is being passed as an argument to
‘ the Find() method. This anonymous method replaces
‘ the need for Step 1, 2 and 3
employee = listEmployees.Find(Function(x As Employee) x.ID = 102)
Console.WriteLine(“ID = {0}, Name {1}”, employee.ID, employee.Name)
Console.ReadLine()

End Sub

‘ Step 1: Create a method whose signature matches
‘ with the signature of Predicate<Employee> delegate
Private Function FindEmployee(ByVal Emp As Employee) As Boolean
Return Emp.ID = 102
End Function

Public Class Employee
Public Property ID() As Integer
Get
Return m_ID
End Get
Set(ByVal value As Integer)
m_ID = value
End Set
End Property
Private m_ID As Integer
Public Property Name() As String
Get
Return m_Name
End Get
Set(ByVal value As String)
m_Name = value
End Set
End Property
Private m_Name As String
End Class
‘=======================================================
‘Service provided by Telerik (www.telerik.com)
‘Conversion powered by NRefactory.
‘Twitter: @telerik
‘Facebook: facebook.com/telerik
‘=======================================================
End Module

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: