Events

An event is a way of providing notifications.
Events are frequently used for objects to indicate a change of state.
Events are declared as Delegates
Event handlers are Delegates.


In C# there is a line of code that tells the compiler which method to call for which event handler.
This means we can give the handler whatever name we want to


All event handlers in C# are required to take parameters (object sender and EventArgs e).


You can use "-" or "-=" to remove an event handler from an event.


Declaring - Explicitly

Using explicit add and remove methods
You can add an event to a class by using the Event declaration.
This declaration includes the name of the event and the argument is uses.
Adding an event to a class specifies that an object of this class can raise this event.

class ClassName 
{
   public delegate void MyNewEvent(string Status);

   private event System.EventHandler EventName
   {
      add { }
      remove { }
   }
}


Declaring - Field Like

This is a way of declaring both a delegate variable and an event all on a single line.

public event System.EventHandler EventName 

is shorthand for

// this is a delegate variable 
   private System.EventHandler _eventname

//this is the event
   public event System.EventHandler EventName
   {
      add
      {
         lock(this)
         {
             _myevent +- value;
         }
      }
      remove { }
      {
         lock(this)
         {
             _myevent -= value;
         }
      }
   }


Add and Remove Methods

Events are often accessed directly through delegates.
The add method is called from this line

eventName += delegateInstance; 

AddHandler object.eventName, AddressOf delegateInstance 

The remove method is called from this line

eventname -= delegateInstance; 

Run-Time Event Handler

To create an event handler at run-time, create an instance of the System.EventHandler delegate and pass it to the corresponding event method

Button1.Click += new System.EventHandler(this.myEventHandler); 
private void myEventHandler()
{
}


The Event is Never Used

To avoid "The event is never used" warning you can explicitly define empty event accessors.


VB.Net

Event Handlers in VB have very specific names.
If the name is not spelt correctly then the subroutine is not called.
These events and event handlers can only be defined at design time (not at run time).
You must specify the classname when you declare the object variable.
You cannot handle shared events as these are not tied to class instances but the class itself.


Important

It is common practice to prefix an event handler with "On" and to use Pascal casing


© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext