linq - C# -Closure -Clarification -


i learning c#.can mean closure a construct can adopt changes in environment in 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 variable id declared in scope of findpersonbyid() t still can access local variable id inside anonymous function (i.e) delegate(person x) { return x.id == id; }

(1) understanding of closure correct ?

(2) advantages can closures?

yes code inside of findpersonbyid taking advantage of closure using parameter id within lambda expression. strictly speaking definitions of closures bit more complex @ basic level correct. if want more information on how function encourage read following articles

the primary advantage of closures demonstrated above. allows write code in more natural, straight forward fashion without having worry implementation details of how lambda expression generated (generally)

consider example how code have write in abscence 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 of express concept of using parameter inside of delegate.


Comments

Popular posts from this blog

java - Jasper subreport showing only one entry from the JSON data source when embedded in the Title band -

mapreduce - Resource manager does not transit to active state from standby -

serialization - Convert Any type in scala to Array[Byte] and back -