Wednesday, August 03, 2005

What is delegate in C#

Delegate is a class, NOT a method. It is a class inherited from System.Delegate or System.MulticastDelegate, which has two properties called "Target" and "Method". The target is the class instance on which the current delegate invokes the instance method, if it is null, it means it's a "Static" calling. MethodInvoker or EventHander are two special delegates treated in a fast manner by Invoke and BeginInvoke. MethodInvoker takes no parameters and returns no value, and EventHandler takes two parameters and returns no value.

1 comment:

Unknown said...

When a delegate is created,the compiler generates three methods for you, Invoke, BeginInvoke and EndInvoke. Invoke is used to execute the delegate synchronously (i.e. a line of code such as myDelegate(); is actually compiled as myDelegate.Invoke();). The other two methods are for asynchronous execution, and must always be called as a pair - every BeginInvoke must be matched by a call to EndInvoke somewhere to guarantee that you don't leak resources.