Delegates and events are powerful features in C# that enable you to implement a form of publish-subscribe pattern, allowing one class to notify other classes when certain actions or events occur. Here's a basic tutorial on how to use delegates and events in C#.
1. Understanding Delegates:
1.1 What is a Delegate?
A delegate is a type-safe function pointer that can reference a method. It allows you to treat methods as first-class objects, providing a way to pass methods as parameters or store them in variables.
1.2 Declaring a Delegate:
public delegate void MyDelegate(string message);
1.3 Using Delegates:
public class MyClass{public void DisplayMessage(string message){Console.WriteLine($"Message: {message}");}}// ...MyClass obj = new MyClass();MyDelegate delegateObj = new MyDelegate(obj.DisplayMessage);// Invoking the delegatedelegateObj("Hello, delegates!");
2. Understanding Events:
2.1 What is an Event?
An event is a mechanism that enables a class to provide notifications to other classes when certain things happen.
2.2 Declaring an Event:
public class Publisher{public event MyDelegate MyEvent;public void RaiseEvent(string message){MyEvent?.Invoke(message);}}
3. Using Delegates and Events Together:
public class Subscriber{public void Subscribe(Publisher publisher){// Subscribe to the eventpublisher.MyEvent += HandleEvent;}public void HandleEvent(string message){Console.WriteLine($"Subscriber received message: {message}");}}// ...class Program{static void Main(){Publisher publisher = new Publisher();Subscriber subscriber = new Subscriber();// Subscribe to the eventsubscriber.Subscribe(publisher);// Raise the eventpublisher.RaiseEvent("Event triggered!");Console.ReadLine();}}
4. Explanation:
Delegates:
MyDelegateis declared, representing a method that takes a string parameter. You can create an instance of this delegate and assign it to a method with a matching signature.Events:
MyEventis an event in thePublisherclass. It uses theMyDelegatedelegate as its type. TheRaiseEventmethod is used to invoke the event.Subscribing to Events: The
Subscribemethod in theSubscriberclass subscribes to the event in thePublisherclass. TheHandleEventmethod is the event handler, which will be called when the event is raised.Main Method: In the
Mainmethod, instances ofPublisherandSubscriberare created. The subscriber subscribes to the publisher's event, and then the publisher raises the event.
This basic example illustrates the fundamental concepts of delegates and events in C#. You can further explore topics like multicast delegates, custom event arguments, and more as you advance in your understanding of these powerful features.