Delegates are like pointers to the method. That means they point to the method's address, which we can call the method. A delegate type is defined using the following three parts.
- The name of the method on which a delegate calls.
- Any argument (if any) of a method.
- The return value (if any) of a method.
Let's look at a simple Publish and Subscribe model using delegates.
IPublisher.cs
public interface IPublisher
{
public delegate void DateTimeDelegate(DateTime dt);
public void OnDataPublished();
}
The IPublisher interface defines the structure of our publisher class. We have a delegate DateTimeDelegate which will accept DateTime parameter.
ISubscriber.cs
public interface ISubscriber
{
public void DisplayDate(DateTime date);
}
And our ISubscriber interface defines the structure of the Subscriber class. DisplayDate method accepts parameter type matching with the delegate we declared in IPublisher interface.
Publisher.cs
public class Publisher : IPublisher
{
private event IPublisher.DateTimeDelegate _datetimeEvent;
public void OnDataPublished()
{
while (true)
{
if (_datetimeEvent != null)
_datetimeEvent(DateTime.Now);
Task.Delay(1000).Wait();
}
}
public void Subscribe(IPublisher.DateTimeDelegate dateTimeDelegate)
{
_datetimeEvent += dateTimeDelegate;
}
}
In our publisher class, _datetimeEvent parameter of type IPublisher.DateTimeDelegate is being assigned to a parameter of type IPublisher.DateTimeDelegate in Subscribe method.
Subscriber.cs
public class Subscriber: ISubscriber
{
public void DisplayDate(DateTime date)
{
Console.WriteLine("DateTime Today" + date);
}
}
The subscriber class defines the DisplayDate method which simply prints the date.
We have our publisher and subscriber ready, to connect the dots, in program.cs file add the lines below.
var publisher = new Publisher();
var subscriber = new Subscriber();
publisher.Subscribe(subscriber.DisplayDate);
publisher.OnDataPublished();
Here we are calling publisher.Subscribe method by passing subscriber.DisplayDate as the parameter. OnDataPublished() method call triggers the event. In other words, it calls the delegated method subscriber.DisplayDate().
This is a short explanation of delegates to know more about delegates and events stay tuned, until then keep coding :)