Thursday, June 19, 2008

C# Puzzle No.4 (intermediate)

It is common to use the lambda expression syntax. Whenever a method is required expecting a parameter and returning something, you can provide

parameter => expression

instead of boring



ReturnType Foo( ParameterType parameter )
{
    expression;
}

and then compiler will interfere types for you for both parameter and expression.


The question is, how do you provide lambda expressions for delegates which expects no parameters?



delegate int FooDelegate();
static void Foo( FooDelegate Delegate )
{
    Console.WriteLine( Delegate() );
}
 
static void TheProblem()
{
   Foo( * );
}

Your goal is to fill the * above with the lambda expression equivalent to following delegate:



int ConvertThisToLambdaExpression()
{
  return 5;
}

2 comments:

apl said...

Not sure if I understand the question correctly, but you can express parameterless lambdas with an empty bracket:

() => 5

Wiktor Zychla said...

yes, this is the correct answer. thank you for providing correct answers for all other puzzles.

I just hope you didn't spoil anyone's fun ;)

regards,
Wiktor