September 18, 2006

Delegates

Delegates

Delegates are similar to C++'s function pointers, as it says on the tin a pointer to a function.
The beauty of delegates and function pointers is that you can throw it around in different classes without that class having knowledge of the object to which the function belongs.

Here's a simple example:


declare your delegate in some class.

public delegate void DelegateFunc();// you must have a func with the same signature


now create a function in another class with same return type and same parameters.

class DelegateClass
{
public static void TheRealDelegateFunc()
{
}
}

now call the delegate from the first class


public delegate void DelegateFunc();// you must have a func with the same signature

static void Main(string[] args)
{
DelegateFunc df = new DelegateFunc(DelegateClass.TheRealDelegateFunc);
df.Invoke();

}

Notice the Invoke() function, this is required to run the function.


http://en.csharp-online.net/index.php?title=CSharp_Delegates_and_Events



System.Delegate and MulticastDelegate
The System.Delegate class also has to very useful methods which allow to you store delegates for invokation later. System.Delegate.Combine(..) and System.Delegate.Remove(..).
Combining 2 or more delagates allows invokation later, the Combine method returns a MulticastDelegate instance which can simple be invoked by calling the instance with the correct parameters, this then calls all the delegates with the matching signature that have been added using the Combine method.







No comments: