Delegates and Events - in COBOL and C# and VB.NET

C# COBOL VB.NET
delegate void MessageHandler(string message);

class DelegatesEvents
{
  static event MessageHandler MessageArrived;

  static void Main()
  {
    // explicit delegate construction
    new MessageHandler(MyHandler);

    // implicit delegate construction
    MessageHandler handler = MyHandler;

    // subscribe to an event
    MessageArrived += MyHandler;

    // raise the event
    MessageArrived("Test message");

    // unsubscribe from the event
    MessageArrived -= MyHandler;

    // Throws a null reference exception as there are no subscribers
    MessageArrived("Test message 2");

    // Safely raising an event
    MessageHandler handler2 = MessageArrived;
    if (handler2 != null)
    {
        handler2("Safe message");
    }
  }

  static void MyHandler(string message)
  {
    System.Console.WriteLine(message);
  }
}
delegate-id MessageHandler (str as string).
end delegate.

class-id DelegatesEvents.

01 MessageArrived     event type MessageHandler static.

method-id Main static.
  *> explicit delegate construction
  invoke new MessageHandler(MyHandler)

  *> implicit delegate construction
  declare handler as type MessageHandler = method MyHandler

  *> subscribe to an event
  attach method MyHandler to MessageArrived

  *> raise the event
  invoke MessageArrived("Test message")

  *> unsubscribe from the event
  detach method MyHandler from MessageArrived

  *> Throws a null reference exception as there are no subscribers
  invoke MessageArrived("Test message 2")

  *> Safely raising an #event
  declare handler2 as type MessageHandler = MessageArrived
  if handler2 not equals null
     invoke handler1("Safe message")
  end-if

end method.

method-id MyHandler static (str as string).
  display str
end method.

end class.
Delegate Sub MessageHandler(ByVal message As String)

Class DelegatesEvents

  Shared Event MessageArrived As MessageHandler

  Shared Sub Main()
    ' explicit delegate construction
    new MessageHandler(AddressOf MyHandler)

    ' implicit delegate construction
    Dim messageHandler As MessageHandler = AddressOf MyHandler

    ' subscribe to an event
    AddHandler MessageArrived, AddressOf MyHandler

    ' fire the event
    RaiseEvent MessageArrived("Test message")

    ' unsubscribe from the event
    RemoveHandler MessageArrived, AddressOf MyHandler

    ' Deosn't throw an exception, even when there are no subscribers
    RaiseEvent MessageArrived("Test message 2")
  End Sub

  Shared Sub MyHandler(message As String)
    System.Console.WriteLine(message)
  End Sub

End Class