Delegate in C#

Delegate is a way that we can declare a variable that holds a reference to a function in our program.  It gives us an opportunity to change the function that will be called at a run time.  Besides, Delegate gives us a way to logically separate different parts of our application from each other, without having to know, in advance, what all the modules are.

Delegate is very handy when it comes to its dynamic.  It can be dynamically chained together and called in order one after the other.

In this post, I will talk about General Delegate, Anonymous Delegate and Composable Delegate, respectively.


General Delegate

public delegate int MyDelegate(int i, string s);

int MyFunction(int i, string s) 
{
//Function implementation, which shares the same signature //with the delegate
}

//Somewhere in the program
MyDelegate f = MyFunction;
int result = f(100, "Hellow");

As we can see in the above code, function MyFunction shares the same signature(Same return type and Same Parameters) with delegate MyDelegate. Somewhere in the program, we declared a variable f that holds a reference to the method MyFunction.

We don’t need to call the full name of the MyFunction when it is needed; instead, we use the variable name and its parameters.


Anonymous Delegate

Anonymous Delegate is a simplified delegate approach, which comes handy when we don’t have to call the delegate a lot of times in our development.

public delegate int MyDelegate(int i, string s);

MyDelegate f = delegate(int i, string s) 
{
//Implementation
}

//Later call the delegate
int result = f(100, "Hello");

As we can see from the above code, we don’t need to write another separate function and implementation. Instead, we provide an implementation of the delegate method straight away, after we declare the variable.


Composable Delegate

As we mentioned before, the Delegate can be dynamically chained together and get called one after another. In this case, Composable Delegate comes to be handy and helpful.

namespace ComposableDelegates
{
    // declare the delegate type
    public delegate void MyDelegate(int arg1, int arg2);

    class Program
    {
        static void func1(int arg1, int arg2)
        {
            string result = (arg1 + arg2).ToString();
            Console.WriteLine("The number is: " + result);
        }
        static void func2(int arg1, int arg2)
        {
            string result = (arg1 * arg2).ToString();
            Console.WriteLine("The number is: " + result);
        }
        static void Main(string[] args)
        {

            MyDelegate f1 = func1;
            MyDelegate f2 = func2;
            MyDelegate f1f2 = f1 + f2;

            // call each delegate and then the chain
            Console.WriteLine("Calling the first delegate");
            f1(10, 20);
            Console.WriteLine("Calling the second delegate");
            f2(10, 20);
            Console.WriteLine("\nCalling the chained delegates");
            f1f2(10, 20);

            Console.WriteLine("\nCalling the unchained delegates");
            f1f2 -= f1;
            f1f2(20, 20);

            Console.WriteLine("\nPress Enter Key to Continue...");
            Console.ReadLine();
        }
    }
}

Terminal Output

As we can see from the code above, delegate f1 practices a plus function and delegate f2 practices a multiply function. We chain delegate f1 and delegate f2 by the following line of code:

MyDelegate f1f2 = f1 + f2;

As a result of chaining delegate f1 and f2, the two functions run one after the other. We can see the result from the terminal output as below:

We don’t only can chain delegates, but also unchain delegates. In the above code, we unchain the delegates by the following code:

f1f2 -= f1;

As a result, the f1f2 is only practising multiply function, and the parameter is (20, 20). In the terminal, the result is 400 as below:


Composable Delegate with Reference Parameter

In composable delegate practice, we don’t only can chain delegates, but also we can pass the amend parameter as well. We can do that by adding keyword ref in front of the parameter.

namespace ComposableDelegates2
{
    // using reference parameters enables results to be passed 
    // along from one delegate to the next
    public delegate void MyDelegate(int arg1, ref int arg2);

    class Program
    { 

        static void Main(string[] args)
        {
            static void func1(int arg1, ref int arg2)
            {
                string result = (arg1 + arg2).ToString();
                arg2 += 20; // arg2 is a ref parameter, so this will change it
                Console.WriteLine("The number is: " + result);
            }
            static void func2(int arg1, ref int arg2)
            {
                string result = (arg1 * arg2).ToString();
                Console.WriteLine("The number is: " + result);
            }

            int a = 10, b = 10;
            MyDelegate f1 = func1;
            MyDelegate f2 = func2;
            MyDelegate combined = f1 + f2;

            Console.WriteLine("The value of b is: {0}", b);
            combined(a, ref b);
            Console.WriteLine("The value of b is: {0}", b);

            Console.WriteLine("\nPress Enter Key to Continue...");
            Console.ReadLine();
        }
    }
}

As we can see in the code above, f1 is practising a plus function, and f2 is practising a multiply function; we can see the keyword ref in front of parameter arg2 in both functions. In the consecutive delegate chain, arg2 value will be passed from one to another.

In this case, delegate combine chain delegate f1 and delegate f2.

combined(a, ref b);

In the code snippet above, we run the delegate f1 in the beginning, which gives us the resulting number is 20; meanwhile, the value of b is 30. Delegate f2 is called after delegate f1’s execution, and b’s value is 30, which is also passed in delegate f2.

As a result, the result number is 300 from 10 * 30.


5 Replies to “Delegate in C#”

  1. Thank you for every one of your hard work on this web page. My aunt really loves making time for investigations and it’s really obvious why. Most of us learn all of the lively mode you offer priceless suggestions through this web site and even increase participation from some other people on the matter so our favorite girl is now starting to learn a lot of things. Take advantage of the rest of the year. You are always doing a remarkable job.

  2. I am just writing to make you understand what a perfect experience my wife’s girl encountered browsing the blog. She came to understand a lot of details, including how it is like to have a great coaching character to get certain people completely comprehend a variety of complex issues. You actually did more than her desires. I appreciate you for coming up with such essential, dependable, edifying and cool guidance on that topic to Ethel.

  3. I’m just commenting to let you be aware of of the excellent discovery my cousin’s child enjoyed going through your blog. She discovered a wide variety of details, most notably how it is like to have a very effective coaching heart to get many more effortlessly fully understand certain complicated matters. You actually did more than my desires. I appreciate you for displaying such great, healthy, educational and also cool guidance on that topic to Evelyn.

  4. My wife and i have been so peaceful when Michael managed to finish up his researching via the precious recommendations he obtained using your web site. It is now and again perplexing to simply happen to be making a gift of tactics which people may have been selling. So we keep in mind we have got the writer to give thanks to for that. The most important illustrations you have made, the simple web site navigation, the relationships you will help to foster – it’s got many overwhelming, and it’s really leading our son in addition to the family know that the situation is exciting, which is rather mandatory. Thank you for everything!

Leave a Reply

Your email address will not be published. Required fields are marked *