Monday, May 6, 2013

C# Lambda Expressions

A lambda expression is an anonymous function that you can use to create delegates or expression tree types. By using lambda expressions, you can write local functions that can be passed as arguments or returned as the value of function calls. See Lambda Expressions (C# Programming Guide).

Lambda expressions are supported by the dot42 compiler. The Calculator code sample demonstrates the use of lambda expressions by creating handlers voor de button click events.


While this article includes code snippets only, the full code sample is included with dot42. Install dot42 and then open the sample from [MyDocuments]\dot42\Samples\Various\Calculator.

Handling the button click event

The click event of the add, subtract, multiply and divided buttons are all handled by the same method Calc but per button instance a different argument is passed:
protected override void OnCreate(Bundle savedInstance)
{
  ...

  btn = (Button)FindViewById(R.Ids.cmdAdd);
  btn.Click += (s, x) => Calc(Operations.Add);
  btn = (Button)FindViewById(R.Ids.cmdSub);
  btn.Click += (s, x) => Calc(Operations.Sub);
  btn = (Button)FindViewById(R.Ids.cmdMul);
  btn.Click += (s, x) => Calc(Operations.Mul);
  btn = (Button)FindViewById(R.Ids.cmdDiv);
  btn.Click += (s, x) => Calc(Operations.Div);
}

private void Calc(Operations operation)
{
  Calc();
  this.operation = operation;
  leftOperand = rightOperand;
  rightOperand = 0;
  FormatValue();
}
Note that without lambda expressions, you would either have to define a different method per button or the operation (+, -, *, /) would somehow have to be encoded in the event source.

1 comment:

  1. tried to use lambda in Activity.RunOnUiThread() but didn't work. Do you plan to allow this?

    ReplyDelete