Delegates in C#

In C and C++, you would have heard of pointer which point to some variable or function. Delegate in C# is a similar concept. They are reference type variables that hold the reference to some function. Delegates in C# are particularly used for implements callbacks and events which are backbone of GUI based programming.

To create a delegate, keyword delegate is used followed by the return type of the function that delegate will refer, then name of the delegate and the parameters. The parameters should be same and in the same order as is the case with the function that will be referenced by the delegate. Havea look at the following example to understand this concept.

´╗┐using System;

namespace CSharpTutorials {
    // Delegate is created here
    public delegate int PerformMaths(int num1,int num2);

    public class MathematicsOperations {
        public int AddNum(int a, int b)  {
            return a + b;

        }
        public int SubNum(int a, int b) {
            return a - b;
        }
        public int MulNum(int a, int b) {
            return a * b;
        }

        public int DivNum(int a, int b){
            return a / b;
        }
    }

    class Tutorial {
        static void Main(string[] args)  {
            
            MathematicsOperations mo = new MathematicsOperations();

            // Delegate variable declaration and referencing the function to call
            PerformMaths mathfunction = new PerformMaths(mo.AddNum);
            // making the call to function by passing parameters.
            Console.WriteLine(mathfunction(20, 10));

            mathfunction = new PerformMaths(mo.SubNum);
            Console.WriteLine(mathfunction(20, 10));

            mathfunction = new PerformMaths(mo.MulNum);
            Console.WriteLine(mathfunction(20, 10));

            mathfunction = new PerformMaths(mo.DivNum);
            Console.WriteLine(mathfunction(20, 10));

            Console.ReadKey();
        }
    }
}

Download the code

In the above example a delegate PerformMaths has been declared at the top. This delegate has a return type of int and receives two integer type parameters. This means that this delegate can point to any method that has a return type of integer and accepts two integer type variable. Next a class MathematicsOperations has been defined. This class contains four methods which receive two integer type arguments, perform some mathematical operation on them and return the result in integer form. This means that our delegate can refer to all of these methods.

Our delegate type variable mathfunction can refer to these methods by passing these functions (without parameter) to the delegate constructor. Next the fucntion can be called by passing parameters to the delegate variable itself.

<<< ArrayList C# ClassEvents in C# >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .