NHead
NHead

Reputation: 129

C# lambda syntax

I have used lambda syntax before but I keep seeing the following kind of syntax and I am not sure how to interpret this. Are there are more conventional ways of writing these so I can compare the two and understand better?

This is one of the examples I have seen:

client.ExecuteAsync(request, (response, asyncHandle) =>
{
    Assert.NotNull(response.Content);
    Assert.Equal(val, response.Content);
    resetEvent.Set();
});

This is another example:

client.SearchAsync("Getting", s => {
    Assert.IsNotNull(s);
    Assert.AreEqual(1, s.Count);
  },
  Assert.IsNull);

Is there a way of writing these without lambda so I can understand them?

Upvotes: 0

Views: 120

Answers (1)

brz
brz

Reputation: 6016

In this example, Lambdas are like methods. This is a roughly equivalent code:

private SomeMethod(List<string> s)
{
    Assert.IsNotNull(s);
    Assert.AreEqual(1, s.Count);
}

clientSearchAsync("Getting", SomeMethod, Assert.IsNull);

In a nutshell, you're passing SomeMethod to SearchAsync method as a parameter, and SearhAsync invokes it in its body.

Upvotes: 3

Related Questions