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#?
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"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With