articles

Home / DeveloperSection / Articles / Introducing Delegates in C#

Introducing Delegates in C#

Chris Anderson 5509 02-Feb-2013

Delegates in C# allow you to dynamically change the reference of the methods in a class. Consider an example of a coffee vending machine, which dispenses different flavors of coffee, such as Cappuccino and black coffee. On selecting the desired flavor of coffee, the vending machine decides to dispense the ingredients, such as milk powder. All the materials are placed in different containers inside the vending machine. The required material is dispensed when you select a flavor.A delegate is a type that represents references to methods with a particular parameter list and return type. When you instantiate a delegate, you can associate its instance with any method with a compatible signature and return type. You can invoke (or call) the method through the delegate instance.

Delegates are used to pass methods as arguments to other methods. Event handlers are nothing more than methods that are invoked through delegates. You create a custom method, and a class such as a windows control can call your method when a certain event occurs.

Suppose, you select black coffee, the vending machine will call methods to dispense hot water and coffee powder only. The reference to these methods is made dynamically, when you press the required button to dispense black coffee.

A delegate is a reference type variable, which holds the reference to a method. This reference can be changed at runtime, as desired. Although, delegates are a general purpose mechanism for indirectly calling methods at runtime, their primary use in C# programming for implementing events and the call-back methods.

To implement delegates in your application you need to declare delegates, instantiate delegates and use delegates.

Declaring Delegates

The methods that can be referenced by a delegate are determined by the delegate declaration. The delegate can refer to the methods, which have the same signature as that of the delegate.

Consider the following example of delegate declaration:

public delegate void MyDelegate (string s)

In the preceding example, the declared delegate type can be used to reference any method. This method should have a single parameter of string type and it does not return any value.

The following syntax is used for delegate declaration:

delegate <return type><delegate-name><parameter list>

Instantiating Delegates

Create the delegate object of the delegate type, which you have already created. Assign the address of the required method to the delegate object. This can be done by calling the constructor of the delegate class and passing the method name. The following example shows how to assign the address of a method to a delegate variable:

public void DelegateFunction(string PassValue)

        {
            //Method implementation Here
        }
        //Delegate Declaration
        public delegate void MyDelegate(string ArgValue);

        public void UseMethod()
        {
            //Delegate Instantiation
            MyDelegate DelegateObject = new MyDelegate(DelegateFunction);
        }

 In the preceding example, the signature and return type of DelegateFunction matches while the delegate declaration of the MyDelegate delegate. The MyDelagate delegate can hold the address of DelegateFunction. DelegateObject is a delegate object of the type, MyDelegate. The address of the DelegateFunction is assigned to the DelegateObject by passing, the name of the function to the delegate constructor.

Using Delegate

You can call the delegate by giving the name of the delegate and by passing parameters, if required. Using delegates is similar to calling methods.

Consider a situation where you need to print information to a file and a screen. There is some common information that needs to go to the file and to the screen. There is also some specific information for both. The methods to print the information to the file and screen are different. You can call these methods at runtime by passing the common information.

The following example shows how to use a delegate:

//This code is to print data to the output device, which is either a file

//or a screen
using System;
using System.IO;

//Program to write the data to the console and file
namespace DelegateExample
{
    public class PrintToDevice
    {
        static FileStream FStream;
        static StreamWriter SWriter;

        //Delegate Declaration
        public delegate void PrintData(string s);

        //Method to print a string to the console
        public static void WriteConsole(string str)
        {
            Console.WriteLine("{0} Console", str);
        }

        //Method to print a string to a file
        public static void WriteFile(string s)
        {
            //Initializing stream object
            FStream = new FileStream("d:\\StoreData.txt",
                FileMode.Append, FileAccess.Write);
            SWriter = new StreamWriter(FStream);
            s = s + " File";
            //Writing a string to the file
            SWriter.WriteLine(s);
            //removing the content from the buffer
            SWriter.Flush();
            SWriter.Close();
            FStream.Close();
        }

        //Method to send the string data to respective methods
        public static void DisplayData(PrintData PMethod)
        {
            PMethod("This should go to the");
        }

        static void Main(string[] args)
        {
            //Initializing the Delegate object

            PrintData Cn = new PrintData(WriteConsole);
            PrintData Fl = new PrintData(WriteFile);
            //Invoking the DisplayData method with the
            //Delegate object as the argument
            DisplayData(Cn);
            DisplayData(Fl);
            Console.ReadLine();
        }
    }
}

 

In the preceding example, the WriteConsole() and WriteFile() methods are used to write the information to the screen and to the file. The delegate variable Print Data is used to refer to the WriteConsole() and WriteFile() methods.


Updated 30-Nov-2017
hi I am software developer at mindstick software pvt. ltd.

Leave Comment

Comments

Liked By