One of the new features of C# in the upcoming Whidbey release are anonymous methods. What they are and how they work is clearly explained in the gotdotnet page Vijay pointed to in his blog. And Don Box uses them reguarly in his blog. Take this snippet taken from the page pointed at :
public MyForm()
{
listBox = new ListBox(...);
textBox = new TextBox(...);
button = new Button(...);
button.Click += new EventHandler(sender, e)
{
listBox.Items.Add(textBox.Text);
};
}
}
A new eventhandler is created, the implementation of this eventhandler immediately follows this creation. I am not among the happy few who already have a copy of Whidbey running, but I think you can code like this as well :
public MyForm()
{
listBox = new ListBox(...);
textBox = new TextBox(...);
button = new Button(...);
otherButton = new Button(...);
EventHandler myAnonymousHandler = new EventHandler(sender, e)
{
listBox.Items.Add(textBox.Text);
};
button.Click += myAnonymousHandler;
otherButton.Click += myAnonymousHandler;
}
}
I think that's pretty cool. When describing anonymous methods they are compared to lambda functions found in Lisp and Eiffel. But I have seen something very similar years ago in Clipper, a very more down to earth language.
Clipper started as a compiler for dBase III applications. Quite some interesting things were added to the dBase language, making it, at the time, quite a nice tool to build applications for DOS. In Clipper 5 you had code blocks which were, according to the documentation, unnamed assignable functions. This is a snippet of Clipper code with a code block
MyCodeblock:= { | a, b| c:= a+b, c}
Function UsingBlock(theBlock, param1, param2)
@1,1 SAY EVAL(theBlock, param1, param2)
Return .T.
On the screen will appear the sum of the parameters passed. So a codeblock is a piece of code which can be passed around, just like the EventHandler in C#. Only the Eval function (and two derived ones) could execute it. You could even compile a code block at runtime, like
MyCodeBlock:= &ThisStringContainsCode
That can be done in C# as well but thank goodness, it is a little more organized there.
I don't want to compare C# and Clipper. Actually Clipper is a crude language, all variables are variants and OOP was still being re-invented at the time. Database support is a disaster compared to today's SQL based tools. And a Clipper app behaves horrific in a Windows (NT) environment. For instance, one running Clipper app can literally cripple a terminal server.
But I considered it worth mentioning. Stay tuned.