Anonymous Method

A feature that allows you do define an anonymous method, and a delegate pointing to that method, inline, in a manner similar to AnonymousInnerClasses in JavaLanguage, or LambdaExpressions in many FunctionalProgrammingLanguages (or BlocksInRuby/SmallTalk, etc... you get the picture).

Use this feature now in BooLanguage: See http://boo.codehaus.org/Closures and http://boo.codehaus.org/Callable+Types

 class SomeClass:
     def InvokeMethod():
         x = do():
             MessageBox.Show("Hello")
         x()

Or CsharpLanguage version 2 will have this feature:

For example, the following CeeSharp v1.x code:

 class SomeClass {
    delegate void SomeDelegate();
    public void InvokeMethod() {
       SomeDelegate del = new SomeDelegate(SomeMethod);      
       del(); 
    }
    void SomeMethod() {      
       MessageBox.Show("Hello");
    }
 }

Can be rewritten as follows:
 class SomeClass {
    delegate void SomeDelegate();
    public void InvokeMethod() {
       SomeDelegate del = delegate() {
           MessageBox.Show("Hello");
       };
       del();   
    }
 }

They can also be used to create closures (see WhatIsClosure), and unlike AnonymousInnerClasses, they have no restrictions on which variables from the surrounding lexical environment can be captured. They are true LexicalClosures.

For example, the classic "counter" example of a closure can be implemented as follows:

 using System;
 delegate int Counter();
 class C {
     static Counter MakeCounter() {
         int x = 0;
         Counter result = delegate { return ++x; };
         return result;
     }
     static void Main() {
        Counter counter = MakeCounter();
        Console.WriteLine(counter());
        Console.WriteLine(counter());
        Console.WriteLine(counter());
     }
 }

Here is that same code in BooLanguage (and it runs just as fast):

 callable Counter() as int //declaration is optional
 class C:
static def MakeCounter() as Counter:
x = 0
result = do:
return x+=1
return result

counter = C.MakeCounter() print counter() print counter() print counter()


CategoryCeeSharp


EditText of this page (last edited December 16, 2005) or FindPage with title or text search