C# Delegate Tutorial with Easy Example

In this tutorial you will learn:
  • What is Delegates?
  • How to declare, initialize and invoke Delegates?
  • Easy Programming Example

This article explains how to create and manipulate Delegates in c#. Before starting delegates you must understand what delegate is?

What is Delegate?

You may get numbers of complex reasons of using delegates on different site. I am not going to put a complex paragraph here. In simple word delegates contains the reference to several methods and call them when needed. So, you create numbers of methods as you need and attach it to delegates. At runtime, an event gets fired and delegates dynamically call the function and show the result.

Real World Example

Let me draw a picture for you. For example, what will you do when you are in a railway station and suddenly hear a fire alarm. What would you do? You will run immediately outside of the campus. So, let me put this scenario in delegates.

  1. When you hear fire alarm it is actually an event. As you hear fire alarm you initiate to run() function to escape.
  2. But if you hear an announcement about your train you don't escape and go to the suitable platform to catch the train.
  3. If you hear your name in the announcement that someone is on phone-line and want to talk to you; you go to inquiry counter to attend the phone.
  4. If you hear that train is 6 hours late you may think of a movie meanwhile the time.
So, in real-world example we also react differently based on event or situation. In programming, delegate does the same thing. We create numbers of suitable function and execute them based on Event. fig-delegate  

Some facts about delegates

  1. Delegates are reference type but instead of referencing objects it reference methods.
  2. Delegates have no method body.
  3. Delegates are type-safe, object-oriented and secure.
  4. A Delegate is a function pointer that allows you to reference a method.
  5. Delegates encapsulate methods.
  6. A Function that is added to delegates must have same return type and same signature as delegate.
  7. A Delegate can be created using delegate keyword.
    1. Delegates with no parameter and no return type
      Public delegate TestDelegate();

    2. Delegates with a parameter but no return type
      Public delegate TestDelegate(object obj1, object obj2);

      Or,
      Public delegate TestDelegate(String message)

    3. Delegates with parameters and return type
      public delegate int TestDelegate(object obj1, object obj2);

  8. A delegate has 3 steps
    1. Declaration
    2. Instantiation
    3. Invocation

Programming Example

Here, I am showing you very basic delegates programming. Once you understand how delegates work you will be able to crack complex delegates codes.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    public class TestDelegate
    {
        //Declaration
        //Creating Delegates with no parameters and no return type.
        public delegate void FirstDelegate();

        public void fun1()
        {
            Console.WriteLine("I am Function 1");
        }
        public void fun2()
        {
            Console.WriteLine("I am Function 2");
        }
        public void fun3()
        {
            Console.WriteLine("I am Function 3");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            TestDelegate testdelegate = new TestDelegate();
//Instantiation
            TestDelegate.FirstDelegate fd1 = new TestDelegate.FirstDelegate(testdelegate.fun1);
            TestDelegate.FirstDelegate fd2 = new TestDelegate.FirstDelegate(testdelegate.fun2);
            TestDelegate.FirstDelegate fd3 = new TestDelegate.FirstDelegate(testdelegate.fun3);

//Invocation 
           fd1();
            fd2();
            fd3();

            Console.ReadKey();
        }
    }
}

Output
I am Function 1
I am Function 2
I am Function 3
_

Explanation

  1. In this programming Example, I have created a delegate
     public delegate void FirstDelegate();

  2. I have also created 3 functions
    public void fun1()
    public void fun2()
    public void fun3()

  3. In the main function creates an object of delegates. You must remember that a delegate always requires a function while initialized.
    TestDelegate.FirstDelegate fd1 = new TestDelegate.FirstDelegate(testdelegate.fun1);
    TestDelegate.FirstDelegate fd2 = new TestDelegate.FirstDelegate(testdelegate.fun2);
    TestDelegate.FirstDelegate fd3 = new TestDelegate.FirstDelegate(testdelegate.fun3);

  4. Finally call the delegates to execute the function.
    fd1();
    fd2();
    fd3();

Example 2

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DelegateExample
{
    class Program
    {
        public delegate int calculator(int x, int y);

        static int Addition(int a, int b)
        {
            return a + b;
        }
        static int Subtraction(int a, int b)
        {
            return a - b;
        }
        static void Main(string[] args)
        {
            calculator c = new calculator(Program.Addition);
            Console.WriteLine("Addition of 5 and 10 is : {0}", c(5, 10));

            calculator d = new calculator(Program.Subtraction);
            Console.WriteLine("Subtraction of 5 and 10 is : {0}", d(5, 10));

            Console.ReadKey();
        }
    }
}

Output
Addition of 5 and 10 is : 15

Subtraction of 5 and 10 is : -5

Summary

In this chapter, you learned what is delegates and how to use it in programming. In the next chapter, you will learn about multicast delegates with example.

More Articles

 

Share your thought