Search code examples
c#lambdaanonymous-methods

Translating anonymous methods into lambda expression


If I would translate this anonymous method:

Func<int, int> f = delegate(int i)
{
     return i + 1;
};

into a lambda expression, it would like this:

Func<int, int> f = i => i + 1;

(I know: this lambda expression will secretly generate another anonymous method (by the compiler), but that is not the point).

Now I want to translate the following method into a lambda expression:

Func<int, int> f = delegate(int i)
{
     Debug.WriteLine("Inside the function!");
     return i + 1;
};

Is there a way and how do I do this?


Solution

  • Lambdas can contain more than one line, the syntax in this case is similar to anonymous delegates from C# 2.0:

    Func<int, int> f = i =>
    {
         Debug.WriteLine("Inside the function!");
         return i + 1;
    };