1

I went through events in Vb.net and i found they are really an amazing feature..but still confused about how to use them effectively.

The real doubt is that the functions and sub could be effective alternative for events. Whatever i do with events i can manage to do it via functions and methods. Wherever there is Raisevent, i can substitute it with a function or procesure. so then, what is the real benefit of events and in which cases i can use them instead of functions and procedures?

  • 2
    Events are used to decouple objects. If you handle an event, the object which holds the event has no idea *who* subscribed to the event. It just gets a "pointer" to a method it invokes when the event is fired. This allows different objects communicate with eachother without knowing any implementation details of the other object. The only thing known are the public interfaces, in this case Events and Event Handlers. – Alex B. Apr 17 '17 at 14:31

2 Answers2

2

Let's see if you understand it with an example. You have the Button control. It defines a lot of events (Click,MouseDown,Keypress...). When you put a button in a Form, you decide there what are the events you want to manage. So in the form you can do something when a button is clicked, or not doing anything.

Imagine if this was done with regular methods. In that case, the button should have a reference to the form where the button is, and the form should have a Click method, is it using it or not.

The event driven programing makes very easy to define some Events to signal when something happens in a class, and is the class that creates the instance the one that decides if that event is relevant or not.

Pikoh
  • 7,582
  • 28
  • 53
0

thank you for clarification, I got the point. The point I Missed was that : event is fired in the same class, but execution is done in a different class.

I mean, when I define a class, I can put RaiseEvent somewhere to recognize something, but I correlate the event with a sub in a different class.

so, in such a class called Wallet I can put a statement like :

    If Dollars > 5 Then
        RaiseEvent Above5()
    End If

and in such different class called AllWallet :

Dim WithEvents myWallet as new Wallet
Sub myWallet_Above5() Handles myWallet.Above5
    MsgBox("Dollars are more than 5")
End Sub

otherwise, I mean if events are fired in the same class they are defined in , the sub and functions can substitute events.

thanks to all

  • A class should not be handling it's own events. Events are normally intended for notifying something outside the class that something has happened as in your example. The point is, when a class raises an event, it does not know what the subscriber of the event will do, nor should it care. – Chris Dunaway Apr 18 '17 at 17:46