Delegates in C#

Submitted by: Submitted by

Views: 455

Words: 675

Pages: 3

Category: Science and Technology

Date Submitted: 05/29/2008 08:44 AM

Report This Essay

Pointer is a variable, which stores address of some memory location. The memory location can be the storage for some value or beginning of function. When it points to function, it is function pointer. Function pointer has address of the function.

Function pointers are not safe. In thousand lines of code, if we have to invoke the function using function pointer, we cannot assure that the pointer points to function without going through the code.

We cannot ensure the number of parameters to the function or the order of parameters. Order of parameters refer to data types. What will happen if we invoked a function with function pointer & pointer is not pointing to function? What will happen if we invoked a function with function pointer & number of arguments are more or less passed? What will happen if we invoked a function with function pointer & order of parameters is wrong? (e.g. Function accepts int first & we pass string first.)

In all cases, our application will crash. In essence, Function pointers are not type-safe.

.NET has got a concept of delegates which are type-safe function pointers with ability to point to multiple functions. Delegates are declared in C# using keyword delegate.

public delegate void DisplayDelegate(string msg);

Declaration of delegate is just like function declaration. That is, the delegate must be declared with return data type & parameters. Parameter names are not relevant.

Internally, a class "DisplayDelegate" is generated which derives from System.MulticastDelegate. System.MulticastDelegate derives from System.Delegate. System.Delegate is the base class. One can create the object of "DisplayDelegate" class. The constructor accepts the function which has same signature as that of delegate declaration.

using System;

namespace DelegateDemo{public delegate void DisplayDelegate(string msg);class Program{ static void Main(string[] args) { DisplayDelegate del = new DisplayDelegate(Show);...