Home > DeveloperSection > Blogs > Delegates in c#

Delegates in c#


C# C# 
Ratings:
0 Comment(s)
 2042  View(s)
Rate this:

Delegates in c# 

 

In this blog I am  trying to exploring the concept of Delegate in c#.

A delegate in C# is similar to a 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.

Type-safe, and secure:   the delegate it fully type-safe unlike function pointers in other host languages, where function pointer actually point the memory block. In c# delegate or function pointer defines the delegate of particular method signature. Thus no object can call/refer to method of another type except it was defined by itself. So the delegate is object oriented type-safe and secure. 

A delegate declaration defines a type that encapsulates a method with a particular set of arguments and return type. For static methods, a delegate object encapsulates the method to be called. For instance methods, a delegate object encapsulates both an instance and a method on the instance. If you have a delegate object and an appropriate set of arguments, you can invoke the delegate with the arguments.

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.

Types  of Delegates in C# : There  are two type delegate is  C#

       1. Single cast Delegate

       2. Multicast Delegate

How to Use/ implements Delegate:

Prototype of delegate:

<access specifier >delegate< return type> <delegate name>(<argument1>,<argument.2>,……<argument.N>);

Declaration of delegate:

We can declare the delegate in same manner in as we declare class; the only deference is that class contains various elements; while delegate defines only the method signature what it had being pointed.

Visibility of delegate :

 It defined anywhere in program depends on the need of delegate. (I.e. it could be declared inside the class, also inside the name space or any other blocks).

How to declare delegate

 Public delegate  void  myDelegate( string message);

declares a new delegate type. Each delegate type describes the number and types of the arguments, and the type of the return value of methods that it can encapsulate. Whenever a new set of argument types or return value type is needed, a new delegate type must be declared.

Instantiating a delegate  

 Once a delegate type has been declared, a delegate object must be created and associated with a particular method. Like all other objects, a new delegate object is created with a new expression. When creating a delegate, however, the argument passed to the new expression is special — it is written like a method call, but without the arguments to the method.

The following statement:

myDelegate  newDel=new myDelegate(<methods name call by  it>);

Example:

Single cast Delegate:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace dummyExamples

{

    class Program

    {

        public delegate int  mathOperation(int arg);

       // public delegate void del(string msg);

        static void Main(string[] args)

        {

            Console.Clear();

            //create delegate instances

            TestDelegate td = new TestDelegate();

            //beacause this method is static and

            //nc1 points to "TestDelegate.AddNum" method

            mathOperation nc1 = new mathOperation(TestDelegate.AddNum);

            //beacause this method is static and

            //nc2 points to "TestDelegate.MulNum" method

            mathOperation nc2 = new mathOperation(TestDelegate.MultNum);

            //beacause this method is  non static and

            // so we need to create object of "TestDelegate"class

            //nc3 points to "td.divideNum" method

            mathOperation nc3 = new mathOperation(td.divideNum);

            //beacause this methos is local to the class ans static

            mathOperation nc4 = new mathOperation(Progarm.returnNum);

            //calling the methods using the delegate objects

            //call the method by passing 25 to AddNum

            // beacuse it nc1 point to"TestDelegate.AddNum"

            nc1(25);

            Console.WriteLine("Value of Num: {0}", nc1(25));

            //call the method by passing 5 to MultNum

            // beacuse it nc2 point to"TestDelegate.MulNum"

            nc2(5);

            Console.WriteLine("Value of Num: {0}", nc2(5));

            //call the method by passing 2 to divideNum

            // beacuse it nc3 point to"td.AddNum"

            nc3(2);

            Console.WriteLine("Value of Num: {0}", nc3(2));

            Console.WriteLine("Value of Num: {0}", nc4(2));

            Console.ReadKey();

        }               

           public static  int returnNum(int returnNum)

           {

               return(returnNum);

           }         

     }

    class TestDelegate

    {

        static int num = 10;

        public static int AddNum(int p)

        {

            num += p;

            return num;

        }

        public static int MultNum(int q)

        {

            num *= q;

            return num;

        }

        public static int getNum()

        {

            return num;

        }

        public int divideNum(int d)

        {

            return (100/ d);

        }

}

  }

Multicast delegate:

 Multicast delegate is same as single cast delegate, as name suggest a bit deference is that in multicasting delegate has a power to calls multiple (more than one method) method with same signature. While in single cast delegation the delegate object can call single method.

Delegate's ability to multicast means that a delegate object can maintain a list of methods to call, rather than a single method 
if you want to add a method to the invocation list of a delegate object, you simply make use of the overloaded += operator, and if you want to remove a method from the invocation list you make use of the overloaded operator -=.
Note: The Multicast delegate here contain methods that return void, if you want to create a multicast delegate with return type you will get the return type of the last method in the invocation list. Also multicasting is performed on same type of delegates.

Example to illustrate multicasting of delegate

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace multiCastingDelegate

{

    class Program

    {

        public delegate int mathOperation(int num);

        static void Main(string[] args)

        {

            //create delegate instances

            mathOperation nc;

            mathOperation nc1 = new mathOperation(AddNum);

            mathOperation nc2 = new mathOperation(MultNum);           

            nc = nc1;

            nc += nc2;//multicating of delegate(adding method list )

            //calling multicast

            //nc(5);

            Console.WriteLine("Value of Num: {0}", getNum());

            nc = nc1;

            nc -= nc2;//multicating of delegate(removing method list )           

            Console.WriteLine("Value of Num: {0}", getNum());           

            Console.WriteLine("Value of Num: {0}", getNum());

             //calling multicast again

            nc(5);

            Console.WriteLine("Value of Num: {0}", getNum());

            Console.ReadKey();

        }

        static int num = 10;

        public static int AddNum(int p)

        {

            num += p;

            return num;

        }

        public static int MultNum(int q)

        {

            num *= q;

            return num;

        }

        public static int getNum()

        {

            return num;

        }

    }

}


Don't want to miss updates? Please click the below button!

Follow MindStick