C# Events and Delegates.

C# Events and Delegates.

Delegates

A delegate is an object that refers to a method or a reference type that defines a method signature. It is declared using the delegate keyword.

def.png

class program
{
    public delegate void MyAgedelegate(int d);//define a delegate
 static void Main(string[] args)
    {
        MyAgedelegate d1 =method1; // methods subscribe to same signature MyAgeDelegate
        d1(5);
    }
public static void method1 (int i)
    {
        Console.WriteLine($"I am {i} years old");
    }

}

Output

2022-05-06 11_40_46-E__CNprojects_Blogs_Blogs_bin_Debug_Blogs.exe.png The instance of the method1 can be called as many times as with different values.

d1(5);
d1(18);
d1(45);
d1(85);
d1 (20);

Output

yrs.png

Delegates in Events

Delegates in Events determine the signature of the event handler method in the subscriber class. A subscriber in events means a class that receives the event, while the publisher class raises or sends the events. Therefore delegates determine the agreement or contract between the publisher and the subscriber. Delegates allows implementation of events for sending messages between different objects that do not need to know about each other.

Events.

Events in C# allows communication between objects , It is internally built on delegates and declared using the event keyword. Events are based on Eventhandlers, delegate and EventArgs base class. They help in building loosely coupled applications and are raised by controls such as buttons. Examples of include key press,clicks etc. The += operator is used to subscribe to an event and -+ operator is used to unsubscribe to an event.

  • Example:
 dm.mySampleEvent += onMyEventRaised()  //Subscribe
 dm.mySampleEvent -= onMyEventRaised()    //Unsubscribe
  • An example of a class that holds the event*
class Demo
{
    //Declare delegate
    public delegate void mySampleDelegate(object sender, EventArgs e);
    //Declare event
    public event mySampleDelegate mySampleEvent;
    //Create a method that raises the  event
    public void raiseEvent()
    {
       //raise event 
       mySampleEvent?.Invoke();
    }
}

It is possible to create as many classes as possible that subscribes to the Event without affecting other classes.

//Create a class that subscribes to mySampleEvent
class firstClass
{
    //instance of class demo
     Demo dm = new Demo();
    //subscribe to the event
    dm.mySampleEvent += onMyEventRaised()

        public void onMyEventRaised
    {
       //method do something 
    }
}

Events with Eventhandler.

.Net provides an inbuilt delegate callled EventHandler. Eventhandler signature is defined as :

Public delegate void Eventhandler(object sender, EventArgs e);

This means there is no need of declaring the delegate while creating an Event class.

  • For Example:
class Demo
{
     //Eventhandler is an inbuilt delegate
    //Declare event
    public event Eventhandler mySampleEvent;
    //Create a method that raises the  event
    public void raiseEvent()
    {
       //raise event 
       mySampleEvent?.Invoke();
    }
}

Creating Custom Data in Events.

Custom data can be created using EventArgs by deriving a class from EventArgs as the base class.

  • For Example:
//declare your own argument type 
    public class DemoArgs : EventArgs
    {
        public int Age{ get; set; };
        public string Name { get; set; }
    }

Then use your own argument type while declaring an event.

class Demo
{
     //use customdata created DemoArgs in the event.
    //Declare event
    public event Eventhandler<DemoArgs> mySampleEvent;
    //Create a method that raises the  event
    public void raiseEvent()
    {
       //raise event 
       mySampleEvent?.Invoke();
    }
}