Wednesday, July 26, 2006

C# 2.0 new features: Delegates

Delegates

A delegate is an important element of C# and is used in every type of .NET application. A delegate is a class whose object (delegate object) can store a set of references to methods. This delegate object is used to invoke the methods. The DotNetFrameWork has a Name Space System.Delagate. We have two flavors of delegate in C#.

  • Single Delegate
  • Multi-cast Delegate

A delegate is called a single delegate that derives from the System.Delegate class contains an invocation list with one method. A delegate is called Multi-cast Delegate that derives from the System.MulticastDelegate contains an invocation list with multiple methods.

syntax:

public delegate return_data_type method_name (arguments);

note: A Delegate may appear either with arguments or without arguments.

Example:

The following should be the definition for delegate. It should present in appropriate class file. (Ex., we have it in class file called exclass)

public delegate string StringDelegate(string s);

And in the main class, we need to assign it like,

objexclass.StringDelegate;

The following code will be executed in the appropriate event handlers.

objexclass.StringDelegate("Hello");

No comments:

Post a Comment