DEV Community

Cover image for Unleashing the Power of Delegates in C#: Boost Your Programming Skills
Ravina Deogadkar
Ravina Deogadkar

Posted on

Unleashing the Power of Delegates in C#: Boost Your Programming Skills

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.

  1. The name of the method on which a delegate calls.
  2. Any argument (if any) of a method.
  3. 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();
}
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

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;
        }

    }
Enter fullscreen mode Exit fullscreen mode

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);
        }
    }
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

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 :)

Top comments (0)