Working with Delegates in C#
 
Published: 05 Apr 2007
Abstract
In this article Joydip discusses what delegates are with lucid code examples.
by Joydip Kanjilal
Feedback
Average Rating: 
Views (Total / Last 10 Days): 39057/ 84

Introduction

Delegates in C# are like functions pointers in C/C++. A multi cast delegate can refer to several methods. A delegate can be used to invoke a method, the call to which can only be resolved or determined at runtime. This article discusses what delegates are and how they can be used in C# with lucid code examples.

What are delegates and why are they required?

Delegates are function pointers in C# that are managed and type safe and can refer to one or more methods that have identical signatures. Delegates in C# are reference types. They are type safe, managed function pointers in C# that can be used to invoke a method that the delegate refers to. The signature of the delegate should be the same as the signature of the method to which it refers. According to MSDN, "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."

C# provides support for Delegates through the class called Delegate in the System namespace. Delegates are of two types.

·         Single-cast delegates

·         Multi-cast delegates

A Single-cast delegate is one that can refer to a single method whereas a Multi-cast delegate can refer to and eventually fire off multiple methods that have the same signature.

The signature of a delegate type comprises are the following.

·         The name of the delegate

·         The arguments that the delegate would accept as parameters

·         The return type of the delegate

A delegate is either public or internal if no specifier is included in its signature. Further, you should instantiate a delegate prior to using the same.

The following is an example of how a delegate is declared.

Listing 1: Declaring a delegate

public delegate void TestDelegate(string message);

The return type of the delegate shown in the above example is "void" and it accepts a string argument. Note that the keyword "delegate" identifies the above declaration as a delegate to a method. This delegate can refer to and eventually invoke a method that can accept a string argument and has a return type of void, i.e., it does not return any value. You can use a delegate to make it refer to and invoke a method that has identical signature as the delegate only. Even if you are using multi-cast delegates, remember that you can use your delegate to refer to and then fire off multiple methods that have identical signatures only.

A delegate should always be instantiated before it is used. The following statement in Listing 2 shows how you can instantiate a delegate.

 

 

Listing 2: Instantiating a delegate

TestDelegate t = new TestDelegate(Display);
Implementing Delegates in C#

This section illustrates how we can implement and use delegates in C#. The following is an example of a delegate that is used to refer to a method of identical signature as the delegate and eventually invoke the method using the delegate.

Listing 3: Implementing a single-cast delegate

using System;
public delegate void TestDelegate(string message); //Declare the delegate
class Test
{
  public static void Display(string message)
  {
    Console.WriteLine("The string entered is : " + message);
  }
  static void Main()
  {
    TestDelegate t = new TestDelegate(Display); //Instantiate the delegate
    Console.WriteLine("Please enter a string");
    string message = Console.ReadLine();
    t(message); //Invoke the delegate
    Console.ReadLine();
  }
}

Refer to the code in Listing 3 above. Note how the delegate has been instantiated. The delegate should be passed the method name as argument when instantiating it to indicate the method that it would be referring to. Further, note that the signature of the delegate "TestDelegate" and the method that it refers to, i.e., "Display", have identical signatures.

You can also assign the references of multiple methods to a delegate and use it to invoke multiple methods. Such a delegate is called a multi-cast delegate as multiple method references are cast to it and then the delegate is used to invoke these methods. The following code example illustrates how a multi-cast delegate can be implemented and used.

Listing 4: Implementing a multi-cast delegate

using System;
public delegate void TestDelegate();
class Test
{
  public static void Display1()
  {
    Console.WriteLine("This is the first method");
  }
  public static void Display2()
  {
    Console.WriteLine("This is the second method");
  }
  static void Main()
  {
    TestDelegate t1 = new TestDelegate(Display1);
    TestDelegate t2 = new TestDelegate(Display2);
    t1 = t1 + t2; // Make t1 a multi-cast delegate
    t1(); //Invoke delegate
    Console.ReadLine();
  }
}

On execution of the above program shown in code Listing IV, the following message is displayed:

This is the first method

This is the second method

Note how we have used the delegate instance t1 as a multi-cast delegate by assigning the references of both t1 and t2 to it.

Delegates can also be used for working with events in C#. You can find a nice article here that discusses how we can accomplish event handling using delegates in C#.

References

Conclusion

A function pointer in C/C++ as we all know is one that points to the base address of a function in the memory. Similarly, delegates are C# function pointers that are managed and type safe. This article has had a glimpse at delegates and how they can be used in C#.



User Comments

No comments posted yet.






Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2019 ASPAlliance.com  |  Page Processed at 2019-08-21 6:34:54 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search