Home > DeveloperSection > Blogs > Delegates in C#

Delegates in C#


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

Delegate in C#  


In this blog I am going to explore the basic concept of Delegates in c#.

 Delegate:

Delegate works as function pointer. The delegate point to any function of its defined signature of methods. These function pointer are unlike to   C/C++ are type safe. Here type safety represents that, no other methods except for which delegate defined is called by the delegate (i.e. only those methods can wrapped into delegate, that math the signature of delegate definition.)


Technically delegate are types defined in c# language. These types are used to declare the methods (declaring the method signature.) and the object of this type can initialized by wrapping up the same signature method to be called by the object of delegate.


Delegates are able to calls methods of any type (any class), static methods and others. But the one in order to call any methods from delegate it must match the method signature, which was defined in delegate declarations.

 

There are two types are delegate in c# are as:

1.       Single cast delegate

2.       Multicast Delegate(all delegates must be same type)

Note: multicasting is more effective and meaningful in case of void return type. Otherwise it will not be effective because the value return by the one delegate could not be stored. So each time firstly added delegate will be in effects. Thus always use multicasting of delegate with void method signatures.

 

Let’s take a demo example to illustrate both types of delegates

using System;

public delegate int MathOperation(int num1, int n2);

public delegate void DisplyMessage(string msg);

namespace DelegateDemo

{

    class Program

    {

        static void Main(string[] args)

        {

            MathOperation Arithmatic1 = new MathOperation(Math.AddNumber);

            Console.WriteLine("sum=" + Arithmatic1(5, 2));

            MathOperation Arithmatic2 = new MathOperation(Math.MultNumber);

            Console.WriteLine("multiplication=" + Arithmatic2(5, 2));

            /*

             * following lines will be display the multicasting

             */

            MathOperation mo = Arithmatic2 + Arithmatic1;

            Console.WriteLine("--------------MULTICASTING OF MATH OPRATIONS----------");

            Console.WriteLine("Multicast delegate output:" + mo(1, 2));

            /*

            //following methods will generate an error, because this delegate does not

            // defined for wrapping this type of method signature.

            //MathOperation Arithmatic3=new MathOperation(Math.Square);

             Console.Write("sum="+Arithmatic3(5));

            */

            //This line of code show that delegate can call static methods easily

            Console.WriteLine("------------SIMPLE METHOD CALL USING DELEGATE---------");

            DisplyMessage MyMessages1 = new DisplyMessage(Messages.UniversalMessage);

            MyMessages1("universal message");

            DisplyMessage MyMessage2 = new DisplyMessage(new Messages().MorningMessage);

            MyMessage2("morning");

            DisplyMessage localMsg = new DisplyMessage(LocalMessage);

            localMsg("hi i am called from local");

            DisplyMessage dm = MyMessage2 + MyMessages1 + localMsg;

            Console.WriteLine("----------MULTICAST------------------------");

            dm("multicast");

            Console.WriteLine("--------- END MULTICAST------------------------");

            Console.WriteLine("---------- REMOVING fFROM LIST-----------------");

            dm = MyMessage2 - MyMessages1 - localMsg;

            dm("REMAINING METHODS");

            Console.ReadKey();

        }

        public static void LocalMessage(string localmsg)

        {

            Console.WriteLine("Hi!This is local message:" + localmsg);

        }

    }

    class Messages

    {

        public static void UniversalMessage(string msg)

        {

            Console.WriteLine("Hi!Your message is:" + msg);

        }

        public void MorningMessage(String msg)

        {

            Console.WriteLine("Good:" + msg);

        }

    }

    public static class Math

    {

        /// <summary>

        /// This method will not called through delegate

        /// because no delegate is defined to wrap this type of method signature.

        /// </summary>

        /// <param name="n"></param>

        /// <returns></returns>

        public static int Square(int n)

        {

            return n * n;

        }

        public static int AddNumber(int n1, int n2)

        {

            return (n1 + n2);

        }

        public static int MultNumber(int n1, int n2)

        {

            return (n1 * n2);

        }

    }

}

 

The output will be display as follows:


However you can test the result by proper variation in input and registering and deregistering the delegate in case of multicasting.

 

I hope you have been learn basics of delegate and understood how it works. I will explore advance concept of delegate in next forth coming Articles

 

Thanks.

 


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

Follow MindStick