C # -Closure -Clarification

I am learning C #. I mean closing as a construct that can adopt the changes in the environment in which it is defined.

Example:

 List<Person> gurus = new List<Person>() { new Person{id=1,Name="Jon Skeet"}, new Person{id=2,Name="Marc Gravell"}, new Person{id=3,Name="Lasse"} }; void FindPersonByID(int id) { gurus.FindAll(delegate(Person x) { return x.id == id; }); } 

The id variable is declared in the scope of FindPersonByID (), but we can still access the local id variable inside the anonymous function (ie) delegate(Person x) { return x.id == id; } delegate(Person x) { return x.id == id; }

(1) Is my understanding of closure correct?

(2) What are the benefits we can get from closing?

+7
closures c # linq anonymous-methods
source share
1 answer

Yes, the code inside FindPersonByID uses closure using the id parameter in the lambda expression. Strictly speaking, defining closures is a bit more complicated, but at a basic level, this is correct. If you need more information on how they work, I recommend that you read the following articles.

The main benefit of closing is what you demonstrated above. This allows you to write code in a more natural, straightforward way, without worrying about the details of how the lambda expression is generated (usually)

Consider, for example, how much code you would need to write in the absence of closures

 class Helper { private int _id; public Helper(int id) { _id = id; } public bool Filter(Person p) { return p.id == _id; } } void FindPersonsByID(int id) { Helper helper = new Helper(id); gurus.FindAll(helper.Filter); } 

All this is just to express the concept of using a parameter inside a delegate.

+5
source share

All Articles