views:

668

answers:

4

In a question answer I find the following coding tip:-

2) simple lambdas with one parameter:

x => x.ToString() //simplify so many calls

As someone who has not yet used 3.0 I don't really understand this tip but it looks interesting so I would appreciate an expantion on how this simplifies calls with a few examples.

I've researched lambdas so I think I know what they do, however I may not fully understand so a little unpacking might also be in order.

+2  A: 

This basically expands to:

private string Lambda(object x) {
  return x.ToString();
}
Jacob
That's what I thought.Where does it help over calling ToString directly?
David Max
All by itself it doesn't. It depends on the context you use it in.
Christian.K
David: Suppose you want to transform a list of integers to a list of strings. You can write a generalised transformation routine, but it needs a delegate to apply to *each* value in the list - and lambda expressions make it easier to specify that delegate.
Jon Skeet
+21  A: 

When you need to create an instance of a delegate which has a single parameter, lambda expressions allow you to create that delegate "inline" in a very concise manner. For instance, here's code to find a particular person in a list, by their name:

List<Person> list = new List<Person>();
// [..] Populate list here
Person jon = list.Find(p => p.Name == "Jon");

In C# 2.0 you could use an anonymous method which was a little bit more longwinded, but not too bad:

List<Person> list = new List<Person>();
// [..] Populate list here
Person jon = list.Find(delegate(Person p) { return p.Name == "Jon"; });

In C# 1.0 you'd have to create a whole extra method. In addition, if you wanted to parameterise it, you'd have to create a different type, whereas anonymous methods and lambda expressions capture their executing environment (local variables etc) so they act like closures:

public Person FindByName(List<Person> list, String name)
{
    return list.Find(p => p.Name == name); // The "name" variable is captured
}

There's more about this in my article about closures.

While passing delegates into methods isn't terribly common in C# 2.0 and .NET 2.0, it's a large part of the basis of LINQ - so you tend to use it a lot in C# 3.0 with .NET 3.5.

Jon Skeet
A: 
string delegate(TypeOfX x)
{
  return x.ToString();
}
Rinat Abdullin
A: 

Are you familiar with C# 2.0 anonymous methods? These two calls are equivalent (assuming SomeMethod accepts a delegate etc):

SomeMethod(x => x.ToString());

SomeMethod(delegate (SomeType x) { return x.ToString();});

I know which I'd rather type...

Marc Gravell