Sponsored Ad

Wednesday, October 28, 2009

Delegates and events

People often find it difficult to see the difference between events & delegates. C# doesn't help matters by allowing you to declare field-like events which are automatically backed by a delegate variable of the same name. This editorial aims to clarify the matter for you. Another source of confusion is the overloading of the term "delegate". Sometimes it is used to mean a delegate type, & at other times it can be used to mean an instance of a delegate type. I'll use "delegate type" & "delegate instance" to distinguish between them, & "delegate" when talking about the whole topic in a general sense.

Delegate types

In some ways, you can think of a delegate type as being a bit like an interface with a single process. It specifies the signature of a process, and when you have a delegate instance, you can make a call to it as if it were a process with the same signature. Delegates provide other features, but the ability to make calls with a particular signature is the reason for the existence of the delegate concept. Delegates hold a reference to a process, and (for instance methods) a reference to the target object the process should be called on.

namespace DelegateArticle
{
public delegate string FirstDelegate (int x);
public class Sample
{
public delegate void SecondDelegate (char a, char b);
}
}

This code declares two types of delegates. DelegateArticle.FirstDelegate The first is that of a single int parameter and returns a string. The second is DelegateArticle.Sample.SecondDelegate char that takes two parameters and return nothing (because the return type is specified as null).

The rates stated here are derived from System.MulticastDelegate, which in turn derives from System.Delegate. In practice, you see only delegate types that are derived from MulticastDelegate. The difference between the Delegate and MulticastDelegate is largely historical, in beta. NET 1.0, the difference was significant (and annoying) - Microsoft sees the merger of the two types together, but decided it was too late in the release cycle to make a major change. You can almost pretend that only one type.
Any delegate who has inherited members believe their father types, a parameterized constructor of the object and IntPtr and three additional methods: Invoke, BeginInvoke and EndInvoke. Return to the constructor in a minute. The methods are not inherited from anything, because firms vary with the signature of the delegate is declared. Using the previous example code, the first delegate has the following methods:

public string Invoke (int x);
public System.IAsyncResult BeginInvoke(int x, System.AsyncCallback callback, object state);
public string Endinvoke(IAsyncResult result);

0 comments:

Post a Comment

Sponsored Ad

Website Update

Followers