Search content within the blog

Tuesday, April 21, 2009

Delegates and Events in c# -Part I

What are delegates and why are they required?

Delegates are function pointers in C# that are managed and type safe and can refer to one or more methods that have identical signatures. The signature of the delegate should be the same as the signature of the method to which it refers. According to MSDN, "A delegate in C# is similar to a function pointer in C or C++. Using a delegate allows the programmer to encapsulate a reference to a method inside a delegate object. The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked.

Function pointers which are extensively used in c/c++ to points to a function holds only the memory address of the function, it doesn’t carry further information about the function parameters, return type etc. On the other hand .NET framework has introduced a type-safe mechanism called delegates, with automatic verification of the signature by the compiler.

So comparatively delegates add a safety dimension in handling function pointers in .NET.

C# provides support for Delegates through the class called Delegate in the System namespace. Delegates are of two types.

* Single-cast delegates
* Multi-cast delegates

The signature of a delegate type comprises are the following.

* The name of the delegate
* The arguments that the delegate would accept as parameters
* The return type of the delegate

A delegate is either public or internal if no specifier is included in its signature. Further, you should instantiate a delegate prior to using the same.

No comments:

Post a Comment