Events in VB.NET
In this article we will discuss about Event functionality .
Event:
For each Event defined by an event source and event handler. An event source can be either a Class or an Object, there is a private field that is based on the underlying delegate type. if you use this field to track a multicast delegate object. An event source also provides a public registration method that allow you to register as many event handlers as desired. An Event handler is a delegate object that's bounds to handler method. when you create event handler(i.e. delegate object) and register it with event source, the event source simply appends the new event handler to the end of the list. if An event source then uses the private field to call invoke on the multicast delegate, Which will in turn call the registered event handlers.
Creating and Register an Event handler:
Visual Basic .NET provide two way to create an event handler and register it with an event source:
-
Dynamic event binding, which involves the use AddHandler keyword.
-
Static event binding, which involves the use of the WithEvent keyword.
Syntax of dynamic event binding:
AddHandler < Event >,< delegate object>
Coding for dynamic Event:
Public Delegate Sub Vchile(ByVal n1 As String)
Public Class Cars
Public Event configration As Vchile
Public Sub nameofcar(ByVal n1 As String)
If (n1 = "Maruti") Then
RaiseEvent configration(n1)
Else
Console.WriteLine("speed is 140km/h")
Console.WriteLine("Mileage is 14km/lit")
Console.WriteLine("car name is Hyundi")
End If
End Sub
End Class
Public Class Maruti
Public Shared Sub info(ByVal n1 As String)
Console.WriteLine("speed is 100km/h")
Console.WriteLine("Mileage is 14km/lit")
Console.WriteLine("car name is maruti 800 Ac")
End Sub
End Class
Module test
Sub Main()
Dim obj1 As New Cars()
Console.WriteLine("Enter (Maruti) to show information")
Console.WriteLine("Ennter (hyundi) to show information")
Dim x As String
x = Console.ReadLine()
AddHandler obj1.configration, AddressOf Maruti.info
obj1.nameofcar(x)
End Sub
End Module
Output: