C#: delegate and event

April 18, 2006

Ever encountered function pointers in C/C++? Well, ‘delegate’ is C# version of function pointer. Imagine a code like this: int (*pfunc) (CMyObj* obj, int iIndex) in C/C++ can become like this: public delegate int MyFunction ( CMyObj obj, int iIndex ) in C#. And then we can just set the delegate function to any function with the same signature. For instance:

public int Function1 ( int i, char c ) { return 1; }
public int Function2 ( int i, char c ) { return 2; }
public delegate int MyFunction ( int i, char c );

.. later on in the code, you can specify this:

MyFunction = Function1; //legal
MyFunction ( 1, ‘a’ ); // ok and will be redirected to function1
MyFunction = Function2; //legal
MyFunction ( 2, ‘b’ ); //ok and will be redirected to function 2

Another use of delegate is to implement an ‘event’. ‘event’ keyword follows this construct: <access> event <delegated function name> <event name> for instance:

public delegate MouseClickHandler ( object sender, MouseArguments arg);
public event MouseClickHandler OnMouseClick;

Now, here is another unique thing about delegate. It can have multicast. It means that the delegate function can handle not only one function at a time, but as many function as you like. Example:

//from previous
public int Function1 ( int i, char c ) { return 1; }
public int Function2 ( int i, char c ) { return 2; }
public delegate int MyFunction ( int i, char c );

.. rather than doing it like before, we can do this:

MyFunction = Function1; //legal
MyFunction += Function2; //legal. Function2 is added to the multicast list
MyFunction ( 2, ‘b’ ); //ok and will invoke function1 and then function2
MyFunction -= Function1; //remove function1 from the multicast list
 

Thats all for my little findings about C#. 

Advertisements

4 Responses to “C#: delegate and event”

  1. Lesley Says:

    A good site, good short contents of the good work. Congratulations !,

  2. Mamie Says:

    Not much on my mind worth mentioning. What can I say? I haven’t been up to much lately. It’s not important. Oh well.,

  3. Barnaby Says:

    Good work, webmaster! Nice site!,

  4. Lambert Says:

    I have loved your site for its useful and funny content and simple design.,


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: