What is the best way to write a callback? I only need to call 1 function that has the sig of void (string, int); and this would need to invoke a class since i have member objs that i need to process. Whats the best way to write this? in C i would do pass a func pointer and an void*obj. i dislike that and i suspect there is a better way to do this in C#?
A:
C#3.0 introduced lambdas which allow you forgo the declaration of callback (or delegate) signatures. It allows you to do things like:
static void GiveMeTheDate(Action<int, string> action)
{
var now = DateTime.Now;
action(now.Day, now.ToString("MMMM"));
}
GiveMeTheDate((day, month) => Console.WriteLine("Day: {0}, Month: {1}", day, month));
// prints "Day: 3, Month: April"
Samuel
2009-04-04 01:32:31
+2
A:
The standard way of handling (or replacing the need for) callbacks in C# is to use delegates or events. See this tutorial for details.
This provides a very powerful, clean way of handling callbacks.
Reed Copsey
2009-04-04 01:32:35
A:
Is this what you mean?
thatfunc(params, it, wants, Func<myObject> myCallbackFunc)
{
myObject obj = new Object();
myCallbackFunc.Invoke(obj);
//or
myCallbackFunc.Invoke(this);
//I wasn't sure what if myObject contained thatFunc or not...
}
J.13.L
2009-04-04 01:34:01