How Delegates are Related to Events in C#?



Events and delegate work together. An event is a reference to a delegate i.e. when an event is raised, a delegate is called. In C# terms, events are a special form of delegates.
Events play an important part in user interfaces and programming notifications. Events and delegates work hand-in-hand to provide a communication between code from one class to other class. When something happens in one class or one part of the code and other part of the code needs a notification, events are used.

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
namespace delegate_custom_multicast  
{  
class Program  
{  
public delegate void MyDelegate(int a, int b);  
public class XX  
{  
public event MyDelegate MyEvent;  
public void RaiseEvent(int a, int b)  
{  
MyEvent(a, b);  
Console.WriteLine("Event Raised");  
}  
public void Add(int x, int y)  
{  
Console.WriteLine("Add Method {0}", x + y);  
}  
public void Subtract(int x, int y)  
{  
Console.WriteLine("Subtract Method {0}", x - y);  
}  
}  
static void Main(string[] args)  
{  
XX obj = new XX();  
obj.MyEvent += new MyDelegate(obj.Add);  
obj.MyEvent += new MyDelegate(obj.Subtract);  
obj.RaiseEvent(20, 10);  
Console.ReadLine();  
}  
}  
} 

1 Comment's

  • Huzaifa Siddiqui

    asdfas

    06 Apr 2022 02:53 AM |  (0) (0)

Comment Form

Submit Comment