C# delegates tutorial and example

C# delegates allows to use a method like an object. This means that you are able to pass the method as an argument to some other method. This is done by pointing a delegate to a method and passing the delegate as an argument. Then using the delegate you are able to call the method that the delegate is pointing to.

The useful part of delegates is so a method can be passed from one object to another.

As we know a method represents some type of action that an object can do. That action is implemented in the method definition itself within the class the method is declared. With a delegate the implementation of the method or part of the method contained in the class, can be delegated to another class.

Here, we have a simple example to understand delegates. We have a Playlist class that allows to add songs to a playlist. The Playlist class provides a method called ShowPlaylist that prints out all the songs in the playlist.

class Playlist
{
     // code eliminated for brevity
     
    public void ShowPlaylist()
    {
          foreach (Song song in this.list)
          {
               Console.WriteLine("Song Title: {0}". song.Title);       
          }
    }

}

Using the Playlist class ShowPlaylist method will get the full playlist printed.

Let’s introduce delegates to the Playlist class. Using a delegate will allow the the consumer of the Playlist class to implement the logic for showing the playlist.

Here we declare a delegate in the Playlist class which has a sing parameter of type Song

class Playlist
{
     // code eliminated for brevity
     // delegate for showing song
     public delegate bool ProcessPlaylistDelegate(Song song);

...

We need to adjust the ShowPlayList() method to use the ProcessPlaylistDelegate. The ShowPlayList method takes the ProcessPlaylistDelegate as a parameter. Now we can process the Playlist before printing it.

        //show the playlist using another function attached to ProcessPlaylistDelegate
        public void ShowPlaylist(ProcessPlaylistDelegate processPlaylist)
        {
            foreach (Song song in this.list)
            {
                if (processPlaylist(song))
                {
                    Console.WriteLine("Song Title: {0}", song.Title);
                }
            }
        }

Now this class can delegate any processing to another method as long as the return type and parameter type matches the delegate. Below the Program class is using the Playlist class. We declare a new Playlist.ProcessPlaylistDelegate and then we are attaching the getMp3Songs to the delegate.

    class Program
    {
        static void Main(string[] args)
        {
             Playlist playlist1 = new Playlist();

             //add some songs to the playlist

             //use the delegate to process the list before it is printed on the screen
             playlist1.ShowPlaylist(new Playlist.ProcessPlaylistDelegate(GetMp3Songs));
        }

  }

Below is the getMp3Songs method definition. This method only returns the mp3 songs. Therefore the ShowPlaylist will ony print the mp3 songs.

        public static bool GetMp3Songs(Song song)
        {
            //more logic goes here
            return (song.Format == "mp3");
        }

The power of delegates happens when we can process the playlist differently without having to touch the Playlist class. Below we declare 2 other methods in the Program class.

public static bool GetCdSongs(Song song)
 {
 //more logic goes here
 return (song.Format == "CD");
 }

public static bool GetAllSongs(Song song)
 {
 //more logic goes here
 return true;
 }

Now we just need to attach these to the delegates in the Main method. These methods will process the playlist differently. The first method will only include cd songs and the second method will include all the songs. This is just a simple example but we can add as much processing as we require without having to touch the class Playlist.

            playlist1.ShowPlaylist(new Playlist.ProcessPlaylistDelegate(GetCdSongs));

            playlist1.ShowPlaylist(new Playlist.ProcessPlaylistDelegate(GetAllSongs));


Download

Tags: