C#, Functions Creating Functions, with Lambda!

November 6th, 2008 by Mel Leave a reply »

So as my knowledge pertaining to the programming language C# progresses by contributions from the people around me as well as the infinite amount of resources online, I find it more and more fascinating and powerful. It’s sort of the “do-all” language, yet it still does it all in style.

Take this little concept for example. With the use of lambda expressions much like you’d find in any other functional programming language such as F#, F#’s predecessor ML, or Haskell, you can produce some pretty slick functional code right inline with everything else. This also produces an effect that is similiar (if not exactly) known as currying.

The following code uses a set of lambda expressions to create a nested function who takes an int and returns a function that matches the event signature for a Button.Click event. This allows us to dynamicly create a new function for each Button added to the form.

void AddButtons()
{
    // Create a brand new function that takes
    // an int and returns another function that
    // matches the definition of an EventHandler.
    Func<int, EventHandler> func =
        (x) => (sender, args) =>
            MessageBox.Show(x.ToString());
 
    // Add a list of buttons to our control/form
    // giving each a unique Click event.
    for (int i = 0; i < 10; i++)
    {
        Button btn = new Button();
        btn.Click += func(i);    // Add handler
        this.Controls.Add(btn);  // Add the button
    }
}

I know this isn’t the most useful example or most impressive, but it’s still pretty cool and serves as a nice reference. For some more slick examples of code optimization in C# you should check out some of the posts on my buddy Erin’s blog over at Random Bits of Foo.

Advertisement

Leave a Reply