tags:

views:

115

answers:

5

I am a VB programmer working my way into C#. I learned how to create and raise events in vb and am finding that it isnt done the same way in C#. Has anybody come across an article that will help me to understand how to do events in C# and maybe explain why it is different in VB.

Thanks

+6  A: 

Does this help?

VB.NET vs. C# - Delegates / Events

Kyle Rozendo
A: 

The difference is mostly syntactic.

See this handy reference about the differences.

The event handler in VB.NET is declared with the Handling key word appended to the event handler signature. In C# you need to use register it with +=.

In VB.NET you invoke the event with RaiseEvent, in C# you call the delegate directly.

Oded
Thanks for your help Oded
M Murphy
A: 

Reading from:

http://msdn.microsoft.com/en-us/library/aa645739(VS.71).aspx

An event in C# is a way for a class to provide notifications to clients of that class when some interesting thing happens to an object. The most familiar use for events is in graphical user interfaces; typically, the classes that represent controls in the interface have events that are notified when the user does something to the control (for example, click a button).

Events, however, need not be used only for graphical interfaces. Events provide a generally useful way for objects to signal state changes that may be useful to clients of that object. Events are an important building block for creating classes that can be reused in a large number of different programs.

Refer to the article for the rest.

Roberto Aloi
A: 

A good quick general reference for some key differences in syntax can be found here. Search for "events" to get to that section.

Key differences is that VB requires you to use some keywords rather than addition/subtraction to wire up events, but gives you a handles keyword automatically wire a routine to an event. And when passing a delegate, you must use a pointless AddressOf keyword. (Sorry for the editorial, but I think that keyword causes more confusion than it saves!)

Patrick Karcher
Thanks for your comment Patrick
M Murphy
@M no problem. was it . . . worth an upvote? :)
Patrick Karcher
+1  A: 

The main difference is the syntax that's used. Underneath, they use the exact same mechanisms within the CLR.

However, VB.NET provides special syntax via WithEvents and Handles, allowing you to do:

Dim WithEvents button1 As Button

Private Sub button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyButton.Click 
    ' Handle button click
End Sub

C# doesn't provide an equivelent - all events must be explicitly subscribed to via event +=, which is more like VB.NET's AddHandler statement.

Reed Copsey
Thanks for your help Reed
M Murphy