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

     | Home  | Articles  | Categories  | Coders  | Search  | Submit  | Contact Us    
Computer language design is just like a stroll in the park. Jurassic Park, that is. --Larry Wall

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
CR Comments by Cambia Research
advertisement
 
Steve Lautenschlager (steve)
Steve is the founder and creator of Cambia Research. Developing and maintaining the site combines his passions for technology, writing and education.
Steve holds a Ph.D. in particle physics from Duke University, has worked at CERN, the European center for particle physics (where the web was born) and in Microsoft's web division with microsoft.com, msnbc.com and other web properties. Steve is a web consultant specializing in Microsoft.NET technologies. Read more here.


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