0

In Javascript or Flash, I am used to passing callbacks to my button objects like this:

MAIN CLASS

function init() {
   var myButton = new Button("red", doSomething);
}
function doSomething() {
    log("someone clicked our button, but who?");
}

BUTTON CLASS CONSTRUCTOR

function Button(color, callback) {
     addListener(mouseClick, callback);
}

This example is greatly simplified, the point is that you can pass a function name as a parameter to the Button instance. The button will then call that function once it is clicked.

Is this possible in C# ? I've read something about delegates but couldn't figure out a simple example.

Kokodoko
  • 26,167
  • 33
  • 120
  • 197

2 Answers2

0

It is quite simple:

//Declare the function "interface"
delegate string UppercaseDelegate(string input);
//Declare the function to be passed
static string UppercaseAll(string input)
{
return input.ToUpper();
}
//Declare the methode the accepts the delegate
static void WriteOutput(string input, UppercaseDelegate del)
{
    Console.WriteLine("Before: {0}", input);
    Console.WriteLine("After: {0}", del(input));
}

static void Main()
{
WriteOutput("test sentence", new UppercaseDelegate(UppercaseAll));
}
Luc
  • 1,491
  • 1
  • 12
  • 21
0

There does not seem to be a way using the Button class in WinForms to assign a callback in the constructor. But it is fairly easy to do as a second step:

Button myButton = new Button("Text Displayed");
myButton.Click += (sender, args) => SomeFunction();
Mick Bruno
  • 1,373
  • 15
  • 13