User Tools

Site Tools


Lambda expressions, Codeblocks, Anonymous methods

Codeblocks are a datatype in Clipper and Visual Objects (and Vulcan.NET). In .NET there are Lambda expressions for the same purpose. X# permits also the codeblock syntax for lambda expressions and is smart enough to create the correct code.

  • Lambda expressions can be defined as
{ x, y => x * y }

No parentheses are needed. Parameters may also be completely skipped:

{ => Console.WriteLine("Lamda without Parameters") }
  • Parameters for Lambda expressions can also be typed:
{ x as Int, y as Int => x * y }
  • The body for a Lambda expression can be a single expression, expression list or statement list (just like the body for a codeblock)
  • For completeness there is also support for Anonymous Method Expressions (AME) similar to C#. After the DELEGATE keyword the parameters appear between Parentheses and the expression, expressionlist or statement list is delimited with Curly braces.

Note that the parameters for AME must be typed.

DELEGATE ( x as Int, y as Int) { x * y }
  • For AME the parameters are also optional as well as the parentheses:
DELEGATE  { Console.WriteLine("A Delegate without params")}
  • Codeblock parameters now may also be typed. In that case they are treated like Lambda expressions

Some examples of this in use:

FUNCTION TestAnonymous() AS VOID
  LOCAL oForm AS Form
  oForm := Form{}
  // Anonymous method expression with 2 statements. Note that the 
  // first statement must appear on the line following the opening Curly 
  // and the closing curly must be on a separate line after the statements
  // (because the statement list 'eats' the end of lines)
  oForm:Click += DELEGATE(o AS System.Object, e AS System.EventArgs ) { 
                        System.Windows.Forms.MessageBox.Show("Click 1!")   
                        System.Windows.Forms.MessageBox.Show("Click 2!")  
  // Lambda Expression with untyped parameters and single expression
  oForm:Click += { o,e => System.Windows.Forms.MessageBox.Show("Lamda Untyped!") }  

  // Lambda Expression with untyped parameters and single expression.
  // For readability here split over 2 lines with a semicolon that indicates 
  // that the statement is continued on the next line
  oForm:Click += { o as Object,e as EventArgs ; 
                     => System.Windows.Forms.MessageBox.Show("Lamda Typed!") }  


Source: Codeblock syntax and Lambda expressions - X# Forum post by Robert v.d.Hulst

lambda_codeblock_anonymous.txt · Last modified: 2018/01/30 05:10 by wolfgangriedmann