You are viewing this site over HTTP, which is not secure. Please consider switching to HTTPS instead.

QuickCode Sample: Declaring events in C# and VB.NET

Declaring events consistently

I find declaring events in VB.NET much easier than in C#. I can't seem to remember the conventions, and how to use delegates. To save me the effort to reproduce this every time I need an event, and to make sure I use a consistent pattern in both C# and VB.NET, the two following QuickCodes help. The first is event %%eventname%%. When applied to the line

event MatchFound

this expands to

' Delegate for the MatchFound event
Public Event MatchFound As EventHandler
 
' Raise the MatchFound event
Protected Sub OnMatchFound()
  RaiseEvent MatchFound(Me, EventArgs.Empty)
End Sub

in VB.NET, and to

// Delegate for the MatchFound event
public EventHandler MatchFound;
 
// Raise the MatchFound event
protected void OnMatchFound()
{
  if (this.MatchFound != null)
    this.MatchFound(this, EventArgs.Empty);
}

in C#.

Events with custom event arguments

A more complex version eventc %%eventname%% expands the line

eventc MatchFound

to an event declaration with corresponding EventArgs derived class for its arguments;

' Event argument class for the MatchFound event
Public Class MatchFoundEventArgs
  Inherits EventArgs
 
  Public Sub New()
    ' TODO: Insert constructor code here
  End Sub
End Class
 
' The MatchFound event
Public Event MatchFound As EventHandler(Of MatchFoundEventArgs)
 
' Raise the MatchFound event
Protected Sub OnMatchFound()
  RaiseEvent MatchFound(Me, New MatchFoundEventArgs())
End Sub

in VB.NET and to

// Event argument class for the MatchFound event
public class MatchFoundEventArgs : EventArgs
{
  public MatchFoundEventArgs()
  {
    // TODO: Insert constructor code here
  }
}
 
// Delegate for the MatchFound event
public delegate void MatchFoundDelegate(object sender, MatchFoundEventArgs e);
 
// The actual MatchFound event
public event MatchFoundDelegate MatchFound;
 
// Raise the MatchFound event
protected void OnMatchFound()
{
  if (this.MatchFound != null)
    this.MatchFound(this, new MatchFoundEventArgs());
}

in C#.

Copy the sample QuickCodes

Copy this XML fragment to the clipboard, then paste it into QuickCode.NET to get the two patterns event (Simple event) and eventc (Event with argument class), both for C# and VB.NET. (How? Click on the link, view the source to get to the underlying XML, copy that to the clipboard, right-click on the list of QuickCodes in Visual Studio and select Paste.)