Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should i create a callback

Tags:

c#

callback

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#?


2 Answers

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"
like image 64
Samuel Avatar answered Jul 26 '26 20:07

Samuel


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.

like image 36
Reed Copsey Avatar answered Jul 26 '26 18:07

Reed Copsey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!