Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event handling differences between C# & VB.NET

NET gurus... How would you convert this very chunk into VB?

this.timer = new System.Timers.Timer(100);
this.timer.Elapsed+=new System.Timers.ElapsedEventHandler(ManageThreads);
this.timer.Start();

When I use an online converter (Telerik), the middle line converts like this:

Me.timer.Elapsed += New System.Timers.ElapsedEventHandler(ManageThreads)

with 2 errors: 1- "Public eventElapsed is an event and cannot be called directly. Use raiseEvent 2- Delegate requires an Adess Of expression. Do I simply add "Address Of" ?

Any clue warmly welcome.

like image 776
Didier Levy Avatar asked Mar 03 '26 00:03

Didier Levy


2 Answers

The syntax for adding event handlers is very different between C# and VB.NET and as you've discovered Telerik doesn't handle that difference very well.

C# add handler syntax:

<object>.<event> += <event_handler_function>

VB add handler syntax:

add handler <object>.<event>, addressof <event_handler_function>

There is another catch you might run into with VB event handling: The object you're adding an event handler for has to be declared at class-scope. E.g. you cannot add a handler to a locally-created object (within a method) and return it or add it to a collection. So you basically have a class-level temp variable when you need to do things dynamically.

Good luck.

like image 159
Paul Sasik Avatar answered Mar 04 '26 13:03

Paul Sasik


something strange returns this converter

Try: AddHandler Me.timer.Elapsed, AddressOf ManageThreads

Add and remove event handlers dynamically in .NET http://www.thescarms.com/dotnet/EventHandler.aspx

like image 21
Roman Pokrovskij Avatar answered Mar 04 '26 13:03

Roman Pokrovskij



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!