Measuring programming progress by lines of code is like measuring aircraft building progress by weight. --Bill Gates
Welcome to my blog and project site for Microsoft.NET development.

I've been a full time .NET developer for ten years, but I didn't start my professional life as a programmer ... more
Share/Print this page:

Delegate Syntax and Usage in C#

By steve on September 01, 2007.
Updated on January 22, 2012.
Viewed 16,962 times (7 times today).
Article TypesArticle TypesLanguage ElementsLanguage ElementsLanguages
How ToOverviewDelegatesEventsC#

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
}
Back to Top

User Comments (3)

Posted 2009 Jan 12 15:55 PM. reply
Very useful... Thanks!

awake
Replied 2010 May 31 08:02 AM by Surez. reply
this is not suitable for beginners
Posted 2009 Jun 22 07:38 AM. reply
but you didn't mention the usage... :(

chintan, India
Post Your Comment
  You may post without logging in or login here.
Display Name: Required.
Email: Required. Will not be shown. Used for identicon.
Comment:
Allowed tags: <quote></quote>, <code></code>, <b></b>, <i></i>, <u></u>, <red></red>
 
   Please type text as shown in the image at left.