9

In C#, I could do something like this:

EventHandler handler = this.SomeEvent;

...which would allow me to, for example, do:

Delegate[] attachedHandlers = handler.GetInvocationList();

In VB.NET, I can't seem to figure out how to do a similar thing.

This doesn't work:

Dim handler As EventHandler = Me.SomeEvent

...due to the following error:

Public Event SomeEvent(sender As Object, e As EventArgs)' is an event, and cannot be called directly. Use a 'RaiseEvent' statement to raise an event.

But this doesn't work either:

Dim handler As EventHandler = AddressOf Me.SomeEvent

...because:

'AddressOf' operand must be the name of a method (without parentheses).

So how can I actually get an EventHandler from an event in VB.NET? The only idea that's immediately coming to mind is to use reflection, but that seems pretty ridiculous.

Dan Tao
  • 125,917
  • 54
  • 300
  • 447

2 Answers2

9
   Private Event MyEvent()
   Private delegates() As System.Delegate = MyEventEvent.GetInvocationList()

undocumented, found here

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • 1
    Me neither! Seems to be one of the "don't-let-that-a-VB.Net-developer see"-things – Tim Schmelter Nov 05 '10 at 17:51
  • I almost want to downvote it because it's so horrible, but obviously it's not your fault so I'll upvote instead :o) – mrmillsy Dec 17 '14 at 15:13
  • You might prefer the explicit Custom Event declaration syntax described [here](https://msdn.microsoft.com/en-us/magazine/cc163775.aspx#S9). – Adventure Feb 04 '15 at 05:00
1

if you take a look at this How to Attach the Events of an Original Object to a Deep Copied Clone I have a code example on how to get the delegate for the event via reflection. As far as I know, its the only way to do it in VB.

Community
  • 1
  • 1
jasper
  • 3,424
  • 1
  • 25
  • 46