SlideShare une entreprise Scribd logo
1  sur  15
Télécharger pour lire hors ligne
1 
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> 
WPresents 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 calledmethod 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.). 
● 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's method 
group.
5 
Simplified Delegate Instantiation in Action 
<DelegateExamples> 
WPresents 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. 
● The definition of a Delegate type looks a little bit 
like a typedef in C/C++.
7 
WFirst 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! 
● The syntax is similar to ECMAScript's/JavaScript's 
function literals (var f = function(x) { return x * x; }). 
- So in other words, JavaScript has this feature for 
ages.
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 referencescan'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. 
● From within anonymous methods you can refer the enclosing 
scope'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 "capture-class" that also 
holds the anonymous method as instance method. An 
instance of this "capture-class" 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 "capture-class" is gc'd, the captured 
variables (as instance variables) can be gc'd as well. 
● Attention, there is a source of memory leaks: Captured 
references can't be gc'd, as long as the Delegate instance (or 
the "capture-class") wasn't gc'd! And the Delegate instance's 
Target object can not be gc'd as long as the object, to which 
the Delegate instance was advised as event handler wasn't 
gc'd! 
● Another problem: during run time "names" 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
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. 
● 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) 
).
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!) 
● In the development phase of the CLR 2, this 
feature was called "relaxed Delegates".
15 
Thank you!

Contenu connexe

Tendances

Method Handles in Java
Method Handles in JavaMethod Handles in Java
Method Handles in Javahendersk
 
Swift Programming
Swift ProgrammingSwift Programming
Swift ProgrammingCodemotion
 
The JavaScript Programming Language
The JavaScript Programming LanguageThe JavaScript Programming Language
The JavaScript Programming LanguageRaghavan Mohan
 
Introduction to Ruby’s Reflection API
Introduction to Ruby’s Reflection APIIntroduction to Ruby’s Reflection API
Introduction to Ruby’s Reflection APINiranjan Sarade
 
Core Java Certification
Core Java CertificationCore Java Certification
Core Java CertificationVskills
 
Reflection in Ruby
Reflection in RubyReflection in Ruby
Reflection in Rubykim.mens
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript ProgrammingSehwan Noh
 
Javascript basic course
Javascript basic courseJavascript basic course
Javascript basic courseTran Khoa
 
Java apptitude-questions-part-1
Java apptitude-questions-part-1Java apptitude-questions-part-1
Java apptitude-questions-part-1vishvavidya
 
Design patterns illustrated 010PHP
Design patterns illustrated 010PHPDesign patterns illustrated 010PHP
Design patterns illustrated 010PHPHerman Peeren
 
+2 CS class and objects
+2 CS class and objects+2 CS class and objects
+2 CS class and objectskhaliledapal
 
Ghost
GhostGhost
GhostESUG
 
Managing Binary Compatibility in Scala (Scala Days 2011)
Managing Binary Compatibility in Scala (Scala Days 2011)Managing Binary Compatibility in Scala (Scala Days 2011)
Managing Binary Compatibility in Scala (Scala Days 2011)mircodotta
 
Introduction to-csharp
Introduction to-csharpIntroduction to-csharp
Introduction to-csharpSDFG5
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascriptAyush Sharma
 

Tendances (20)

Method Handles in Java
Method Handles in JavaMethod Handles in Java
Method Handles in Java
 
Swift Programming
Swift ProgrammingSwift Programming
Swift Programming
 
C# Delegates
C# DelegatesC# Delegates
C# Delegates
 
The JavaScript Programming Language
The JavaScript Programming LanguageThe JavaScript Programming Language
The JavaScript Programming Language
 
Introduction to Ruby’s Reflection API
Introduction to Ruby’s Reflection APIIntroduction to Ruby’s Reflection API
Introduction to Ruby’s Reflection API
 
Core Java Certification
Core Java CertificationCore Java Certification
Core Java Certification
 
Java For Automation
Java   For AutomationJava   For Automation
Java For Automation
 
Reflection in Ruby
Reflection in RubyReflection in Ruby
Reflection in Ruby
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming
 
Java
JavaJava
Java
 
Javascript basic course
Javascript basic courseJavascript basic course
Javascript basic course
 
Java apptitude-questions-part-1
Java apptitude-questions-part-1Java apptitude-questions-part-1
Java apptitude-questions-part-1
 
Design patterns illustrated 010PHP
Design patterns illustrated 010PHPDesign patterns illustrated 010PHP
Design patterns illustrated 010PHP
 
+2 CS class and objects
+2 CS class and objects+2 CS class and objects
+2 CS class and objects
 
Ghost
GhostGhost
Ghost
 
Managing Binary Compatibility in Scala (Scala Days 2011)
Managing Binary Compatibility in Scala (Scala Days 2011)Managing Binary Compatibility in Scala (Scala Days 2011)
Managing Binary Compatibility in Scala (Scala Days 2011)
 
Swift Programming - Part 2
Swift Programming - Part 2Swift Programming - Part 2
Swift Programming - Part 2
 
Introduction to-csharp
Introduction to-csharpIntroduction to-csharp
Introduction to-csharp
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascript
 
Unit 1 Java
Unit 1 JavaUnit 1 Java
Unit 1 Java
 

En vedette

Madhavashram Bhopal
Madhavashram BhopalMadhavashram Bhopal
Madhavashram BhopalVivek Potdar
 
Building Circuits
Building CircuitsBuilding Circuits
Building Circuitsghbrown
 
μάθημα 1.3 - Μεταγωγή
μάθημα 1.3 - Μεταγωγήμάθημα 1.3 - Μεταγωγή
μάθημα 1.3 - Μεταγωγήedioudi
 
Gestionando la relación con los clientes... más allá del contacto
Gestionando la relación con los clientes... más allá del contactoGestionando la relación con los clientes... más allá del contacto
Gestionando la relación con los clientes... más allá del contactoAMETIC
 
Ascension Parish Home Sales and Prices June 2013 vs June 2014 Prairieville Go...
Ascension Parish Home Sales and Prices June 2013 vs June 2014 Prairieville Go...Ascension Parish Home Sales and Prices June 2013 vs June 2014 Prairieville Go...
Ascension Parish Home Sales and Prices June 2013 vs June 2014 Prairieville Go...Bill Cobb, Appraiser
 
Don’t let aweber get response ban your account!
Don’t let aweber get response ban your account!Don’t let aweber get response ban your account!
Don’t let aweber get response ban your account!digifloss
 
Book@9212612173 Jaypee Greens The Orchards
Book@9212612173 Jaypee Greens The OrchardsBook@9212612173 Jaypee Greens The Orchards
Book@9212612173 Jaypee Greens The OrchardsCandry Johnson
 

En vedette (15)

02
0202
02
 
E commerce cina
E commerce cinaE commerce cina
E commerce cina
 
Madhavashram Bhopal
Madhavashram BhopalMadhavashram Bhopal
Madhavashram Bhopal
 
Building Circuits
Building CircuitsBuilding Circuits
Building Circuits
 
3C so
3C so3C so
3C so
 
μάθημα 1.3 - Μεταγωγή
μάθημα 1.3 - Μεταγωγήμάθημα 1.3 - Μεταγωγή
μάθημα 1.3 - Μεταγωγή
 
Gestionando la relación con los clientes... más allá del contacto
Gestionando la relación con los clientes... más allá del contactoGestionando la relación con los clientes... más allá del contacto
Gestionando la relación con los clientes... más allá del contacto
 
Call for papers
Call for papersCall for papers
Call for papers
 
Semana de acogida
Semana de acogidaSemana de acogida
Semana de acogida
 
Ninjas By Joseph
Ninjas By JosephNinjas By Joseph
Ninjas By Joseph
 
Uhy 2011 global tax outlook
Uhy 2011 global tax outlookUhy 2011 global tax outlook
Uhy 2011 global tax outlook
 
Ascension Parish Home Sales and Prices June 2013 vs June 2014 Prairieville Go...
Ascension Parish Home Sales and Prices June 2013 vs June 2014 Prairieville Go...Ascension Parish Home Sales and Prices June 2013 vs June 2014 Prairieville Go...
Ascension Parish Home Sales and Prices June 2013 vs June 2014 Prairieville Go...
 
Don’t let aweber get response ban your account!
Don’t let aweber get response ban your account!Don’t let aweber get response ban your account!
Don’t let aweber get response ban your account!
 
Presentation1
Presentation1Presentation1
Presentation1
 
Book@9212612173 Jaypee Greens The Orchards
Book@9212612173 Jaypee Greens The OrchardsBook@9212612173 Jaypee Greens The Orchards
Book@9212612173 Jaypee Greens The Orchards
 

Similaire à Review of c_sharp2_features_part_ii

Delegates and events
Delegates and eventsDelegates and events
Delegates and eventsIblesoft
 
(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_ii(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_iiNico Ludwig
 
I assignmnt(oops)
I assignmnt(oops)I assignmnt(oops)
I assignmnt(oops)Jay Patel
 
Introduction to C++ Programming
Introduction to C++ ProgrammingIntroduction to C++ Programming
Introduction to C++ ProgrammingPreeti Kashyap
 
(4) c sharp introduction_object_orientation_part_i
(4) c sharp introduction_object_orientation_part_i(4) c sharp introduction_object_orientation_part_i
(4) c sharp introduction_object_orientation_part_iNico Ludwig
 
CJP Unit-1 contd.pptx
CJP Unit-1 contd.pptxCJP Unit-1 contd.pptx
CJP Unit-1 contd.pptxRAJASEKHARV10
 
Application package
Application packageApplication package
Application packageJAYAARC
 
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
 
(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_ii(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_iiNico Ludwig
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorialsakreyi
 
Oop2011 actor presentation_stal
Oop2011 actor presentation_stalOop2011 actor presentation_stal
Oop2011 actor presentation_stalMichael Stal
 
UNIT III.ppt
UNIT III.pptUNIT III.ppt
UNIT III.pptAjit Mali
 
Top 20 c# interview Question and answers
Top 20 c# interview Question and answersTop 20 c# interview Question and answers
Top 20 c# interview Question and answersw3asp dotnet
 
Advanced programming topics asma
Advanced programming topics asmaAdvanced programming topics asma
Advanced programming topics asmaAbdullahJana
 
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)Ovidiu Farauanu
 

Similaire à Review of c_sharp2_features_part_ii (20)

Delegates and events
Delegates and eventsDelegates and events
Delegates and events
 
(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_ii(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_ii
 
I assignmnt(oops)
I assignmnt(oops)I assignmnt(oops)
I assignmnt(oops)
 
30csharp
30csharp30csharp
30csharp
 
30c
30c30c
30c
 
Introduction to C++ Programming
Introduction to C++ ProgrammingIntroduction to C++ Programming
Introduction to C++ Programming
 
(4) c sharp introduction_object_orientation_part_i
(4) c sharp introduction_object_orientation_part_i(4) c sharp introduction_object_orientation_part_i
(4) c sharp introduction_object_orientation_part_i
 
CJP Unit-1 contd.pptx
CJP Unit-1 contd.pptxCJP Unit-1 contd.pptx
CJP Unit-1 contd.pptx
 
Application package
Application packageApplication package
Application package
 
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
 
(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_ii(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_ii
 
Delegates and events in C#
Delegates and events in C#Delegates and events in C#
Delegates and events in C#
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 
Oop2011 actor presentation_stal
Oop2011 actor presentation_stalOop2011 actor presentation_stal
Oop2011 actor presentation_stal
 
UNIT III.ppt
UNIT III.pptUNIT III.ppt
UNIT III.ppt
 
UNIT III (2).ppt
UNIT III (2).pptUNIT III (2).ppt
UNIT III (2).ppt
 
Top 20 c# interview Question and answers
Top 20 c# interview Question and answersTop 20 c# interview Question and answers
Top 20 c# interview Question and answers
 
Unit iii
Unit iiiUnit iii
Unit iii
 
Advanced programming topics asma
Advanced programming topics asmaAdvanced programming topics asma
Advanced programming topics asma
 
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
 

Plus de Nico Ludwig

Grundkurs fuer excel_part_v
Grundkurs fuer excel_part_vGrundkurs fuer excel_part_v
Grundkurs fuer excel_part_vNico Ludwig
 
Grundkurs fuer excel_part_iv
Grundkurs fuer excel_part_ivGrundkurs fuer excel_part_iv
Grundkurs fuer excel_part_ivNico Ludwig
 
Grundkurs fuer excel_part_iii
Grundkurs fuer excel_part_iiiGrundkurs fuer excel_part_iii
Grundkurs fuer excel_part_iiiNico Ludwig
 
Grundkurs fuer excel_part_ii
Grundkurs fuer excel_part_iiGrundkurs fuer excel_part_ii
Grundkurs fuer excel_part_iiNico Ludwig
 
Grundkurs fuer excel_part_i
Grundkurs fuer excel_part_iGrundkurs fuer excel_part_i
Grundkurs fuer excel_part_iNico 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_i
New c sharp3_features_(linq)_part_iNew c sharp3_features_(linq)_part_i
New c sharp3_features_(linq)_part_iNico Ludwig
 

Plus de Nico Ludwig (20)

Grundkurs fuer excel_part_v
Grundkurs fuer excel_part_vGrundkurs fuer excel_part_v
Grundkurs fuer excel_part_v
 
Grundkurs fuer excel_part_iv
Grundkurs fuer excel_part_ivGrundkurs fuer excel_part_iv
Grundkurs fuer excel_part_iv
 
Grundkurs fuer excel_part_iii
Grundkurs fuer excel_part_iiiGrundkurs fuer excel_part_iii
Grundkurs fuer excel_part_iii
 
Grundkurs fuer excel_part_ii
Grundkurs fuer excel_part_iiGrundkurs fuer excel_part_ii
Grundkurs fuer excel_part_ii
 
Grundkurs fuer excel_part_i
Grundkurs fuer excel_part_iGrundkurs fuer excel_part_i
Grundkurs fuer excel_part_i
 
(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_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_ii

  • 1. 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> WPresents 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 calledmethod 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.). ● 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's method group.
  • 5. 5 Simplified Delegate Instantiation in Action <DelegateExamples> WPresents 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. ● The definition of a Delegate type looks a little bit like a typedef in C/C++.
  • 7. 7 WFirst 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! ● The syntax is similar to ECMAScript's/JavaScript's function literals (var f = function(x) { return x * x; }). - So in other words, JavaScript has this feature for ages.
  • 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 referencescan'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. ● From within anonymous methods you can refer the enclosing scope'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 "capture-class" that also holds the anonymous method as instance method. An instance of this "capture-class" 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 "capture-class" is gc'd, the captured variables (as instance variables) can be gc'd as well. ● Attention, there is a source of memory leaks: Captured references can't be gc'd, as long as the Delegate instance (or the "capture-class") wasn't gc'd! And the Delegate instance's Target object can not be gc'd as long as the object, to which the Delegate instance was advised as event handler wasn't gc'd! ● Another problem: during run time "names" 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
  • 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. ● 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) ).
  • 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!) ● In the development phase of the CLR 2, this feature was called "relaxed Delegates".