Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 997
David Max Avatar asked Oct 01 '08 09:10

David Max


3 Answers

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.

like image 165
Jon Skeet Avatar answered Sep 20 '22 14:09

Jon Skeet


This basically expands to:

private string Lambda(object x) {
  return x.ToString();
}
like image 24
Jacob Avatar answered Sep 22 '22 14:09

Jacob


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...

like image 24
Marc Gravell Avatar answered Sep 22 '22 14:09

Marc Gravell