Working with Delegates in C#
page 3 of 5
by Joydip Kanjilal
Feedback
Average Rating: 
Views (Total / Last 10 Days): 26553/ 53

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#.


View Entire Article

User Comments

No comments posted yet.






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


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-04-26 1:53:34 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search