Cambia Research - Supporting the Microsoft .NET Developer Community Supporting the Microsoft .NET Developer Community  

     | Home  | Articles  | Categories  | Coders  | Search  | Submit  | Contact Us    
Any inaccuracies in this index may be explained by the fact that it has been sorted with the help of a computer. --Donald Knuth

Share Your Knowledge! -- Create and submit your articles the easy way with WebWriter.

Updated:12:31 PM CT Sep 01, 2007
Posted:12:31 PM CT Sep 01, 2007

Delegate Syntax and Usage in C#

Author: Steve Lautenschlager

ReferenceBeginnerData TypesEventsC#

 Overview

How do I create a delegate in C#?

Delegate Type Declaration in C#

// simple delegate type declaration
public delegate void MessageHandler(string message);

// with various input parameters
public delegate int CountDaysHandler(CountMethod method, DateTime startDate, DateTime endDate)

Delegate Method Definition in C#

// Defining the delegate

public void HandleMessage(string message)
{
   // do something with the message
}

public int CountDays(CountMethod method, DateTime startDate, DateTime endDate)
{
   // return the number of days between the dates using the desired technique
   return -1;
}

// Define the delegate as an event
public class MyClass
{
   public event MessageHandler OnMessage;
}

Instantiate and Assign the Delegate

// declare a new MessageHandler delegate
private MessageHandler _MyMessageHandler = new MessageHandler(HandleMessage);

private CountDaysHandler _MyCounter = new CountDaysHandler(CountDays);

// register a delegate with an event
MyClass.OnMessage += new MessageHandler(HandleMessage);

// un-register
MyClass.OnMessage -= new MesageHandler(HandleMessage);

// View list of registered delgates
Delegate[] delegateList = OnMessage.GetInvocationList();
foreach (Delegate d in delegateList)
{
   // do something with the delegate
}

Add New Comment
Delegate Syntax and Usage in C#
awake12 Jan 09, 15:55Reply 
re: Delegate Syntax and Usage in C#
Surez31 May 10, 8:02Reply 
Delegate Syntax and Usage in C#
chintan, India22 Jun 09, 7:38Reply 
CR Comments by Cambia Research
advertisement
 
Steve Lautenschlager (steve)
Steve founded Cambia Research to augment his .NET hobby. Developing and maintaining the site combines his interests in technology, writing and education.


 
Copyright © Cambia Research 2002-2007. All Rights Reserved. steve [ at ] cambiaresearch.com