Interesting C# 3.0 Quiz on Lambda Expressions

Found this (slightly old) lambda expression quiz on Bart de Smet’s blog:

Think about the following code fragment and find out how it works (if it works of course):

using System;

class Lambda
{
delegate int BinOp(int a, int b);

static void Main()
{
int c = 3;

int res = Calculate((a,b) => a + b + c, 1, 2);

Console.WriteLine(res);
}

static int Calculate(BinOp op, int a, int b)
{
return op(a,b);
}
}

Hm. Well, let’s take a stab. Converting the lambda expression into a C# 2.0-style anonymous method would give you something like:

int c = 3;
int res = Calculate(delegate (int a, int b) { return a + b + c; }, 1, 2);

Then, taking a step backward to a C# 1.0-style delegate would mean something like:

delegate int BinOp(int a, int b, int c);
//…
int c = 3;
int res = Calculate(Sum, 1, 2, c);
// …
static int Sum(int a, int b, int c)
{
return a + b + c;
}
}

static int Calculate(BinOp op, int a, int b, int c)
{
return op(a,b,c);
}

So, the question is, does this work?  At first glance I don’t see why not.  The final 1.0-style declaration looks obviously doable; my only question is the scoping of the “c” variable in the 2.0-style anonymous declaration.  It’s too late for me to inspect ILDASM output.
Fun exercise!

Advertisements

0 Responses to “Interesting C# 3.0 Quiz on Lambda Expressions”



  1. Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s





%d bloggers like this: