Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does "Custom Event" work in VB.Net?

In C# if I want to create a "Custom Event" you do something like this:

private EventHandler _MyEvent;
Public Event EventHandler MyEvent 
{
   add{ _MyEvent += value; }
   remove{ _MyEvent -= Value; }
}
protected void RaiseMyEvent()
{
   if(_MyEvent != nul)
      _MyEvent(this, EventArgs.Empty);
}

In VB this is not so straightforward nor can I find any help ANYWHERE on the net. This does not work:

private _MyEvent as EventHandler
Public Custom Event MyEvent as EventHandler
   AddHandler(ByVal value as EventHandler)
      _MyEvent += value 'does not work
      addhandler _MyEvent, value 'does not work
      [Delegate].Combine(_MyEvent, value) '_MyEvent still nothing
   End AddHandler
   RemoveHandler(ByVal value as EventHandler)
      'Same kind of stuff here
   End RemoveHandler
   RaiseEvent(sender as Object, e as EventArgs)
      if(_MyEvent IsNot Nothing) Then '_MyEvent is always nothing
         _MyEvent.Invoke(sender, e)
      End If
   End RaiseEvent
End Event

Please help.

like image 994
Micah Avatar asked Dec 23 '08 15:12

Micah


Video Answer


2 Answers

VB takes a lot of the work out of the mix for you.

Simply Declare an event:

Public Event DidSomething(sender as object, e as EventArgs)

Then anywhere in the code, call the falling Raise Event

RaiseEvent DidSomething(me, EventArgs.Empty)
like image 126
Tom Anderson Avatar answered Sep 19 '22 02:09

Tom Anderson


Delegates are immutable, so method "[Delegate].Combine" returns new delegate, but not modify the parameters. So you need:

_MyEvent = [Delegate].Combine(_MyEvent, value)
like image 29
TcKs Avatar answered Sep 19 '22 02:09

TcKs