Working with delegates in C#


working with delegates

In this session we will learn :

  • What is a delegate and why do we need them
  • Action delegate
  • Func delegate


A delegate in C# is similar to function pointer in C or C++ Using a delegate allows the programmer to encapsulate a reference to a method inside a delegate object. The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked. Unlike function pointers in C or C++, delegates are object-oriented, type-safe, and secure.

An interesting and useful property of a delegate is that it does not know or care about the class of the object that it references. Any object will do; all that matters is that the method’s argument types and return type match the delegate’s. This makes delegates perfectly suited for “anonymous” invocation.

In simple terms a delegate is a data type that defines kinds of methods and explains events(which uses delegates),exception, and error handling. A delegate is a data type much similar to a class or a structure. In contrast , a delegate is a type that defines the parameters and returns values of the method.


Understanding the syntax :

The following code shows you can define a delegate type.

[accessibility] delegate returnType DelegateName ([parameters]);

Now lets break the code:

Accessibility : An accessibility for the delegate type such as public or private.

Delegate : The delegate keyword.

returnType : The data type that a method of this delegate type returns such as void , int , string.

DelegateName : The name that you want to give to the delegate.

Parameter : The paramenter list that a method of this delegate type should take.

Let’s understand this by the following example code:

The following example illustrates declaring , instantiating , and using a delegate. The class “MyFirstClass” have 2 methods Add and Length. Add simply concatenates the first name and last name of the object formed in main, and another method called Length that simply returns the length of the string entered of the first name and last name.

The delegate type used is called “MyFirstDelegate” . If we have more than one namespaces and we have classes and want to access the functionality of both the classes having same number of signatures , we can do it by using a delegate.

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

namespace UnderstandingDelegates
    //creating a delegate
    public delegate string MyFirstDelegate(string firstName,string lastName);

    public class MyFirstClass
        public string Add(string a, string b)
            return (a + b);
        public string Length(string a,string b)
            return ((a + b).Length).ToString();

    class Program
        static void Main(string[] args)
            MyFirstClass class1 = new MyFirstClass();

            MyFirstDelegate delegate1 = class1.Add;
            string i = delegate1("Navneet", "Singh");
            Console.WriteLine("Name after concatinating :"+i);

            MyFirstDelegate delegate2 = class1.Length;
            string j = delegate2("Navneet", "Singh");
            Console.WriteLine("Length of name :"+j);


working with delegates

Why do we need delegate : Suppose if we have multiple methods with same signature(return and number of parameters) and we want to call all the methods with single object then we can go for delegates.



The generic Action delegate represent a method  that returns void .Different version of Action take between 0 and 18 parameters , The following code shows the definition of the Action takes two parameters:

Public delegate void Action <in T1, in T2>(T1 arg1, T2 arg2)

The keyword in within the generic parameter list indicates that the T1 and T2 type parameter are contravariant .

Unless you need to define more than 18 parameters, you can use the action instead of creating your own delegates . For example, the code in the previous section defined an EmployeeParameterDelegate type that takes an Employee object as a parameter and returns void. The following code shows two ways you could declare variable of that type:

//method 1

Privater delegate void EmployeeParameterDelegate(Employee employee);

Private EmployeeParameterDelegate EmployeeParameterMethod;



Private Action<Employee>EmployeeParameterMethod2;

This first statement defines the EmployeeParameterDelegate type. The statement after the first comment declares a variable of that type. The statement after the second comment declares a comparable variable of type Action<Employee>.


Func Delegate

The generic func delegate represents a method that returns a value. As is the case with Action, different versions of func take between 0 and 18 input parameters. The following code shows the definition of the Func delegate that takes two parameter :

Public delegate TResult Finc<in T1, in T2 , out TResult>(T1 arg1,T2 arg2)

The three types defined by the generic delegate represent the types of the two parameter and the return value.

The following code shows two ways you could declare variables of that type:

//Method 1

Private delegate Person ReturnPersonDelegate();

Private ReturnPersonDelegate ReturnPersonMethod1;



Private Func<Person> ReturnPersonMethod2;

The code’s first statement defines the ReturnPersonDelegate type . The second after the first comment declares a variable of that type . The statements after the second comment declares a comparable variable of type Func<Person>.


We now have a good understanding of delegates, now we can use delegates for different purposes in windows phone 8 and wpf, which I will demonstrate soon.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

CommentLuv badge