Tuesday, April 27, 2010

How to write callbacks (delegate) in C# and .NET

Copy from:
http://www.myelin.co.nz/notes/callbacks/cs-delegates.html

http://msdn.microsoft.com/en-us/library/Bb985784

http://msdn.microsoft.com/en-us/magazine/cc301810.aspx

If you're used to function pointers in C, a delegate is basically a pair of pointers rolled into one:
  • A pointer to an object (optional)
  • A pointer to a method of that object
That means a single delegate passes all the information needed to locate a function in your program, whether it's a static method or associated with an object.
You define them like this in C#:
public delegate void FooCallbackType( int a, int b, int c );
When you want to use them, you make delegate out of the function you want to call:
class CMyClass
{
 public void FunctionToCall( int a, int b, int c )
 {
  // This is the callback
 }

 public static void Foo()
 {
  FooCallbackType myDelegate = new FooCallbackType(
   this.FunctionToCall );
  // Now you can pass that to the function
  // that needs to call you back.
 }
}
If you want to make a delegate to point to a static method, it just looks the same:
class CMyClassWithStaticCallback
{
 public static void StaticFunctionToCall( int a, int b, int c )
 {
  // This is the callback
 }

 public static void Foo()
 {
  FooCallbackType myDelegate = new FooCallbackType(
   CMyClass.StaticFunctionToCall );
 }
}
All in all, they do the same thing as interface-based callbacks in C++, but cause a bit less trouble because you don't need to worry about naming your functions or making helper objects, and you can make delegates out of any method. They're more flexible.

No comments:

Post a Comment