SlideShare una empresa de Scribd logo
1 de 15
Review of C#2 Features – Part II 
Nico Ludwig (@ersatzteilchen)
2 
TOC 
● Review of C#2 Features – Part II 
– Delegates, Methods and Method Groups 
– Anonymous Methods 
– Variance of Delegates 
● Sources: 
– Jeffrey Richter, Applied Microsoft .Net Framework Programming 
– Jon Skeet, CSharp in Depth
3 
Delegates in C#1 
<DelegateExamples> 
Presents how we work with Delegates in C#1.
4 
Delegates, Methods and Method Groups 
● Delegates are types: A Delegate describes a type of a method. 
– Any Delegate eventually derives from Delegate (MulticastDelegate). 
● A method matching the Delegate can be called by an instance of that Delegate. 
– Similar to function pointers in C/C++. 
– (Multicasting (i.e. a delegate as a collection of methods (an invocation list)) is an extra feature of Delegates.) 
● All overloads of a method visible in the current context are called method group. 
– The method group is a kind of symbolic name of a method. 
● Most important uses of Delegates: 
– Working with events (e.g. in UIs Delegate instances are used as callbacks). 
– Passing around code to be executed in a different thread (Control.Invoke(Delegate), new Thread(ThreadStart), 
ThreadPool.QueueUserWorkItem(WaitCallback) etc.).
5 
Simplified Delegate Instantiation in Action 
<DelegateExamples> 
Presents simplified Delegate Instantiation in C#2.
6 
Simplified Delegate Instantiation 
// New in C#2: create a Delegate instance from a method group: 
aDelegateInstance = Foo; 
// Creating a Delegate instance in C#1: 
aDelegateInstance = new AcceptString(Foo); 
● In C#2 it's allowed to instantiate a Delegate from a method group item directly. 
– I.e. the immediate step to create a Delegate instance can be skipped. 
delegate void EventHandler(object sender, EventArgs e); // The Delegate. 
private void MyForm_Load(object sender, EventArgs e) { /* pass */ } // An event handler. 
// Advise an event handler in C#1: 
Load += new EventHandler(MyForm_Load); 
// New in C#2: advise event handler from a method group: 
Load += MyForm_Load; 
● (Perspective: an Event/delegate object is just a collection of methods in .Net) 
● Event handlers can also be advised from a method group in C#2. 
– I.e. method groups can be chained to combine them to an invocation list directly.
7 
First Example with Anonymous Methods 
<DelegateExamples> 
First example with anonymous methods.
From Simplified Delegate Instantiation to Anonymous Methods 
8 
// Initialization of a Delegate instance the conventional way: 
AcceptString printToConsole = new AcceptString(PrintSomethingToConsole); 
// New in C#2: Initialization of a Delegate instance with an anonymous method: 
AcceptString printToConsole = delegate(string s) 
{ 
Debug.WriteLine(s); 
}; 
● Anonymous methods: Delegate instance code can be inlined completely. 
– I.e. a method can be defined as an anonymous block of code. 
– Similar concepts: Closure (Groovy, Python, ECMAScript), Block (Smalltalk, Ruby, Objective-C) 
– An anonymous method can access outer local contexts/variables (i.e. closures)! 
– The signature of the anonymous method is checked against the Delegate. 
– This is an outstanding feature in C#2!
9 
Anonymous Methods underneath 
<DelegateExamples> 
Anonymous methods underneath.
10 
More on anonymous Methods 
● For each anonymous method the compiler will generate an ordinary method. 
● For anonymous methods the compiler may (MS specific) generate a class. 
– Classes are needed to put closures into effect with locals. 
● Such a class has a method containing the anonymous method's code. 
● Such a class has fields to hold/capture references of the local context respectively. 
● If instance members are accessed in the anonymous method, a field to hold this is added. 
– No class needs to be generated, if no outer locals are being referenced. 
● Then the anonymous method's code is held by an ordinary class or instance method. 
● Attention: The lifetime of captured locals is extended! Captured references can't be garbage collected (gc'd), as long as 
the Delegate instance wasn't gc'd! 
– An anon. method (Delegate instance) has a lexical binding of the enclosing scope's locals and the this reference! -> You can 
access these bindings in the anon. method. 
– If you use these bindings in an anon. method, the bound objects can only be gc'd, if the Delegate instance expressed by the anon. 
method is gc'd.
11 
Everyday use of anonymous Methods 
<DelegateExamples> 
Everyday use of anonymous Methods.
12 
Transporting Code with Delegates 
● Another perception of Delegate instances: a way to pass code to methods. 
● Therefor .Net 2 provides two generic multipurpose Delegate types: 
delegate void Action<T>(T item); // A Delegate describing methods acting on item. 
delegate bool Predicate<T>(T item); // A Delegate describing methods that check a 
● On the opposite some types (e.g. List<T>) provide methods that make use of those new Delegate types e.g.: 
● These new tools provide ways to get rid of explicitly writing loops. 
– But this is just the beginning of the "transporting code" story, in C#3 this concept has been developed to the next level to work w/ 
any enumerable object: with LINQ. 
// predicate on item. 
public void List<T>.ForEach(Action<T> action); // Do action for each item. 
public bool List<T>.RemoveAll(Predicate<T> match); // Remove all items that 
// match the passed Predicate.
13 
Delegate Variance 
<DelegateExamples> 
These examples show Delegate co- and contravariance.
14 
Delegates are variant in C#2 
● Variance expresses compatibility of Delegate instances to a Delegate type, if: 
– the return types of Delegate instance and type are related: as covariance; and if 
– the parameter types of Delegate instance and type are related: as contravariance. 
● Covariant return type: 
– The instance's return type can be more derived than the Delegate type's. 
– I.e. a Delegate instance may "deliver more" than the Delegate type. 
● Contravariant parameter type: 
– An instance's parameter types can be less derived than the Delegate type's. 
– I.e. a Delegate instance may "require less" than the Delegate type. 
– Fine for event handlers: you get more derived EventArgs and deal with the base type. 
● (This has nothing to do with generic variance available in C#4/.Net 4!)
15 
Thank you!

Más contenido relacionado

Más de Nico Ludwig

(1) gui history_of_interactivity
(1) gui history_of_interactivity(1) gui history_of_interactivity
(1) gui history_of_interactivityNico Ludwig
 
(1) gui history_of_interactivity
(1) gui history_of_interactivity(1) gui history_of_interactivity
(1) gui history_of_interactivityNico Ludwig
 
New c sharp4_features_part_vi
New c sharp4_features_part_viNew c sharp4_features_part_vi
New c sharp4_features_part_viNico Ludwig
 
New c sharp4_features_part_v
New c sharp4_features_part_vNew c sharp4_features_part_v
New c sharp4_features_part_vNico Ludwig
 
New c sharp4_features_part_iv
New c sharp4_features_part_ivNew c sharp4_features_part_iv
New c sharp4_features_part_ivNico Ludwig
 
New c sharp4_features_part_iii
New c sharp4_features_part_iiiNew c sharp4_features_part_iii
New c sharp4_features_part_iiiNico Ludwig
 
New c sharp4_features_part_ii
New c sharp4_features_part_iiNew c sharp4_features_part_ii
New c sharp4_features_part_iiNico Ludwig
 
New c sharp4_features_part_i
New c sharp4_features_part_iNew c sharp4_features_part_i
New c sharp4_features_part_iNico Ludwig
 
New c sharp3_features_(linq)_part_v
New c sharp3_features_(linq)_part_vNew c sharp3_features_(linq)_part_v
New c sharp3_features_(linq)_part_vNico Ludwig
 
New c sharp3_features_(linq)_part_iv
New c sharp3_features_(linq)_part_ivNew c sharp3_features_(linq)_part_iv
New c sharp3_features_(linq)_part_ivNico Ludwig
 
New c sharp3_features_(linq)_part_iv
New c sharp3_features_(linq)_part_ivNew c sharp3_features_(linq)_part_iv
New c sharp3_features_(linq)_part_ivNico Ludwig
 
New c sharp3_features_(linq)_part_iii
New c sharp3_features_(linq)_part_iiiNew c sharp3_features_(linq)_part_iii
New c sharp3_features_(linq)_part_iiiNico Ludwig
 
New c sharp3_features_(linq)_part_ii
New c sharp3_features_(linq)_part_iiNew c sharp3_features_(linq)_part_ii
New c sharp3_features_(linq)_part_iiNico Ludwig
 
New c sharp3_features_(linq)_part_i
New c sharp3_features_(linq)_part_iNew c sharp3_features_(linq)_part_i
New c sharp3_features_(linq)_part_iNico Ludwig
 
New c sharp3_features_(linq)_part_i
New c sharp3_features_(linq)_part_iNew c sharp3_features_(linq)_part_i
New c sharp3_features_(linq)_part_iNico Ludwig
 
Review of c_sharp2_features_part_iii
Review of c_sharp2_features_part_iiiReview of c_sharp2_features_part_iii
Review of c_sharp2_features_part_iiiNico Ludwig
 
Review of c_sharp2_features_part_ii
Review of c_sharp2_features_part_iiReview of c_sharp2_features_part_ii
Review of c_sharp2_features_part_iiNico Ludwig
 
Review of c_sharp2_features_part_i
Review of c_sharp2_features_part_iReview of c_sharp2_features_part_i
Review of c_sharp2_features_part_iNico Ludwig
 

Más de Nico Ludwig (20)

(2) gui drawing
(2) gui drawing(2) gui drawing
(2) gui drawing
 
(2) gui drawing
(2) gui drawing(2) gui drawing
(2) gui drawing
 
(1) gui history_of_interactivity
(1) gui history_of_interactivity(1) gui history_of_interactivity
(1) gui history_of_interactivity
 
(1) gui history_of_interactivity
(1) gui history_of_interactivity(1) gui history_of_interactivity
(1) gui history_of_interactivity
 
New c sharp4_features_part_vi
New c sharp4_features_part_viNew c sharp4_features_part_vi
New c sharp4_features_part_vi
 
New c sharp4_features_part_v
New c sharp4_features_part_vNew c sharp4_features_part_v
New c sharp4_features_part_v
 
New c sharp4_features_part_iv
New c sharp4_features_part_ivNew c sharp4_features_part_iv
New c sharp4_features_part_iv
 
New c sharp4_features_part_iii
New c sharp4_features_part_iiiNew c sharp4_features_part_iii
New c sharp4_features_part_iii
 
New c sharp4_features_part_ii
New c sharp4_features_part_iiNew c sharp4_features_part_ii
New c sharp4_features_part_ii
 
New c sharp4_features_part_i
New c sharp4_features_part_iNew c sharp4_features_part_i
New c sharp4_features_part_i
 
New c sharp3_features_(linq)_part_v
New c sharp3_features_(linq)_part_vNew c sharp3_features_(linq)_part_v
New c sharp3_features_(linq)_part_v
 
New c sharp3_features_(linq)_part_iv
New c sharp3_features_(linq)_part_ivNew c sharp3_features_(linq)_part_iv
New c sharp3_features_(linq)_part_iv
 
New c sharp3_features_(linq)_part_iv
New c sharp3_features_(linq)_part_ivNew c sharp3_features_(linq)_part_iv
New c sharp3_features_(linq)_part_iv
 
New c sharp3_features_(linq)_part_iii
New c sharp3_features_(linq)_part_iiiNew c sharp3_features_(linq)_part_iii
New c sharp3_features_(linq)_part_iii
 
New c sharp3_features_(linq)_part_ii
New c sharp3_features_(linq)_part_iiNew c sharp3_features_(linq)_part_ii
New c sharp3_features_(linq)_part_ii
 
New c sharp3_features_(linq)_part_i
New c sharp3_features_(linq)_part_iNew c sharp3_features_(linq)_part_i
New c sharp3_features_(linq)_part_i
 
New c sharp3_features_(linq)_part_i
New c sharp3_features_(linq)_part_iNew c sharp3_features_(linq)_part_i
New c sharp3_features_(linq)_part_i
 
Review of c_sharp2_features_part_iii
Review of c_sharp2_features_part_iiiReview of c_sharp2_features_part_iii
Review of c_sharp2_features_part_iii
 
Review of c_sharp2_features_part_ii
Review of c_sharp2_features_part_iiReview of c_sharp2_features_part_ii
Review of c_sharp2_features_part_ii
 
Review of c_sharp2_features_part_i
Review of c_sharp2_features_part_iReview of c_sharp2_features_part_i
Review of c_sharp2_features_part_i
 

Último

My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 

Último (20)

My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 

Review of c_sharp2_features_part_ii

  • 1. Review of C#2 Features – Part II Nico Ludwig (@ersatzteilchen)
  • 2. 2 TOC ● Review of C#2 Features – Part II – Delegates, Methods and Method Groups – Anonymous Methods – Variance of Delegates ● Sources: – Jeffrey Richter, Applied Microsoft .Net Framework Programming – Jon Skeet, CSharp in Depth
  • 3. 3 Delegates in C#1 <DelegateExamples> Presents how we work with Delegates in C#1.
  • 4. 4 Delegates, Methods and Method Groups ● Delegates are types: A Delegate describes a type of a method. – Any Delegate eventually derives from Delegate (MulticastDelegate). ● A method matching the Delegate can be called by an instance of that Delegate. – Similar to function pointers in C/C++. – (Multicasting (i.e. a delegate as a collection of methods (an invocation list)) is an extra feature of Delegates.) ● All overloads of a method visible in the current context are called method group. – The method group is a kind of symbolic name of a method. ● Most important uses of Delegates: – Working with events (e.g. in UIs Delegate instances are used as callbacks). – Passing around code to be executed in a different thread (Control.Invoke(Delegate), new Thread(ThreadStart), ThreadPool.QueueUserWorkItem(WaitCallback) etc.).
  • 5. 5 Simplified Delegate Instantiation in Action <DelegateExamples> Presents simplified Delegate Instantiation in C#2.
  • 6. 6 Simplified Delegate Instantiation // New in C#2: create a Delegate instance from a method group: aDelegateInstance = Foo; // Creating a Delegate instance in C#1: aDelegateInstance = new AcceptString(Foo); ● In C#2 it's allowed to instantiate a Delegate from a method group item directly. – I.e. the immediate step to create a Delegate instance can be skipped. delegate void EventHandler(object sender, EventArgs e); // The Delegate. private void MyForm_Load(object sender, EventArgs e) { /* pass */ } // An event handler. // Advise an event handler in C#1: Load += new EventHandler(MyForm_Load); // New in C#2: advise event handler from a method group: Load += MyForm_Load; ● (Perspective: an Event/delegate object is just a collection of methods in .Net) ● Event handlers can also be advised from a method group in C#2. – I.e. method groups can be chained to combine them to an invocation list directly.
  • 7. 7 First Example with Anonymous Methods <DelegateExamples> First example with anonymous methods.
  • 8. From Simplified Delegate Instantiation to Anonymous Methods 8 // Initialization of a Delegate instance the conventional way: AcceptString printToConsole = new AcceptString(PrintSomethingToConsole); // New in C#2: Initialization of a Delegate instance with an anonymous method: AcceptString printToConsole = delegate(string s) { Debug.WriteLine(s); }; ● Anonymous methods: Delegate instance code can be inlined completely. – I.e. a method can be defined as an anonymous block of code. – Similar concepts: Closure (Groovy, Python, ECMAScript), Block (Smalltalk, Ruby, Objective-C) – An anonymous method can access outer local contexts/variables (i.e. closures)! – The signature of the anonymous method is checked against the Delegate. – This is an outstanding feature in C#2!
  • 9. 9 Anonymous Methods underneath <DelegateExamples> Anonymous methods underneath.
  • 10. 10 More on anonymous Methods ● For each anonymous method the compiler will generate an ordinary method. ● For anonymous methods the compiler may (MS specific) generate a class. – Classes are needed to put closures into effect with locals. ● Such a class has a method containing the anonymous method's code. ● Such a class has fields to hold/capture references of the local context respectively. ● If instance members are accessed in the anonymous method, a field to hold this is added. – No class needs to be generated, if no outer locals are being referenced. ● Then the anonymous method's code is held by an ordinary class or instance method. ● Attention: The lifetime of captured locals is extended! Captured references can't be garbage collected (gc'd), as long as the Delegate instance wasn't gc'd! – An anon. method (Delegate instance) has a lexical binding of the enclosing scope's locals and the this reference! -> You can access these bindings in the anon. method. – If you use these bindings in an anon. method, the bound objects can only be gc'd, if the Delegate instance expressed by the anon. method is gc'd.
  • 11. 11 Everyday use of anonymous Methods <DelegateExamples> Everyday use of anonymous Methods.
  • 12. 12 Transporting Code with Delegates ● Another perception of Delegate instances: a way to pass code to methods. ● Therefor .Net 2 provides two generic multipurpose Delegate types: delegate void Action<T>(T item); // A Delegate describing methods acting on item. delegate bool Predicate<T>(T item); // A Delegate describing methods that check a ● On the opposite some types (e.g. List<T>) provide methods that make use of those new Delegate types e.g.: ● These new tools provide ways to get rid of explicitly writing loops. – But this is just the beginning of the "transporting code" story, in C#3 this concept has been developed to the next level to work w/ any enumerable object: with LINQ. // predicate on item. public void List<T>.ForEach(Action<T> action); // Do action for each item. public bool List<T>.RemoveAll(Predicate<T> match); // Remove all items that // match the passed Predicate.
  • 13. 13 Delegate Variance <DelegateExamples> These examples show Delegate co- and contravariance.
  • 14. 14 Delegates are variant in C#2 ● Variance expresses compatibility of Delegate instances to a Delegate type, if: – the return types of Delegate instance and type are related: as covariance; and if – the parameter types of Delegate instance and type are related: as contravariance. ● Covariant return type: – The instance's return type can be more derived than the Delegate type's. – I.e. a Delegate instance may "deliver more" than the Delegate type. ● Contravariant parameter type: – An instance's parameter types can be less derived than the Delegate type's. – I.e. a Delegate instance may "require less" than the Delegate type. – Fine for event handlers: you get more derived EventArgs and deal with the base type. ● (This has nothing to do with generic variance available in C#4/.Net 4!)

Notas del editor

  1. A method group is the set of all methods found by a member lookup of a certain method name in a certain context. E.g. all overloads of a method being effectively present due to inheritance from multiple types are part of that method&amp;apos;s method group.
  2. The definition of a Delegate type looks a little bit like a typedef in C/C++.
  3. The syntax is similar to ECMAScript&amp;apos;s/JavaScript&amp;apos;s function literals (var f = function(x) { return x * x; }). - So in other words, JavaScript has this feature for ages.
  4. From within anonymous methods you can refer the enclosing scope&amp;apos;s locals and also the this reference in instance methods of reference types. So in anonymous methods locals and the this reference are bound lexically. MS specific: The local variables will be captured as instance variables of a compiler generated &amp;quot;capture-class&amp;quot; that also holds the anonymous method as instance method. An instance of this &amp;quot;capture-class&amp;quot; is created locally where the anonymous method was written and provides the mentioned instance method as Delegate instance. If this is captured, a field to hold it will be created as well, and this will also be the Target of the Delegate instance (in other cases it is null). When the instance of the &amp;quot;capture-class&amp;quot; is gc&amp;apos;d, the captured variables (as instance variables) can be gc&amp;apos;d as well. Attention, there is a source of memory leaks: Captured references can&amp;apos;t be gc&amp;apos;d, as long as the Delegate instance (or the &amp;quot;capture-class&amp;quot;) wasn&amp;apos;t gc&amp;apos;d! And the Delegate instance&amp;apos;s Target object can not be gc&amp;apos;d as long as the object, to which the Delegate instance was advised as event handler wasn&amp;apos;t gc&amp;apos;d! Another problem: during run time &amp;quot;names&amp;quot; of anonymous methods are obfuscated to unspeakable compiler-generated symbols. These symbols are then visible in stack-traces and in reverse-engineered code. A different way to understand this: anonymous methods a esp. suitable for methods that are not reusable
  5. In .Net 1.x most developers used Delegates (types and instances) for two purposes: Handling events (e.g. in UIs). Passing around code to be executed in a different thread (e.g. by Control.Invoke, or by Thread(ThreadStart), or by ThreadPool.QueueUserWorkItem(WaitCallback)).
  6. In the development phase of the CLR 2, this feature was called &amp;quot;relaxed Delegates&amp;quot;.