New c sharp3_features_(linq)_part_i

Nico Ludwig
Nico LudwigSenior Engineer at Avid Technology à Avid Technology

- Automatically implemented Properties - Object and Collection Initializers: new Ways to initialize Objects and Collections

1 
New C#3 Features (LINQ) – Part I 
Nico Ludwig (@ersatzteilchen)
2 
TOC 
● New C#3 Features – Part I 
– Focus of C#3 Features 
– Automatically implemented Properties 
– Object and Collection Initializers: new Ways to initialize Objects and Collections 
● Sources: 
– Jon Skeet, CSharp in Depth
3 
Changes in .Net 3/3.5 – Overview 
● .Net 3/3.5 runtime 
– All the .Net 3 and 3.5 features are based on .Net 2 features. 
– The CLR wasn't even changed, .Net 3.5 still uses a CLR 2 underneath. 
● .Net 3/3.5 libraries 
– Some new libraries have been added: 
● Windows Presentation Foundation (WPF) 
● Windows Communication Foundation (WCF) 
● Windows Workflow Foundation (WF) 
● Windows CardSpace 
– Some present APIs have been extended. 
● C#3 and VB9 got syntactical enhancements to cope with LINQ. 
– The compilers have been updated, but no changes to the CIL have been done. 
● Windows CardSpace is a system to manage 
different identities against other environments, 
e.g. web sites. CardSpace is like your wallet with 
different cards representing different identities.
4 
Which Aims does C#3 pursue? 
● Focus of C#3 features: 
– Enhance readability and reduce syntactic fluff. 
– Increase productivity: "less code that monkeys could write". 
– More expressiveness to support a functional programming style. 
– LINQ 
● C#3 requires the .Net 3.5 being installed at minimum. 
– As well as Visual Studio 2008 or newer for development. 
● In this presentation: 
– The new boilerplate features of C#3 will be examined.
5 
Automatically implemented Properties 
// Public property Age in C#1/C#2: 
private int _age; 
public int Age 
{ 
get { return _age; } 
set { _age = value; } 
} 
// New in C#3: Age as automatically implemented property: 
public int Age { get; set; } 
● C#3 allows the definition of properties with a simplified syntax. 
– OK, it can only be used to define simple get/set properties with bare backing fields. 
– A real no-brainer, it; reduces the amount of required code. 
– Idea taken from C++/CLI (trivial properties) and Objective-C (synthesized properties). 
– Gotcha: Automatically implemented properties can break serialization. 
– (Not available for indexers. Default values can't be specified on them explicitly.) 
● In principle field-like events are automatically implemented by default since C#1 
– The methods add and remove and the backing field can be implemented optionally. 
● .Net's properties support the so called Unified Access 
Principle (UAP). UAP means that all the data of an object 
can be accessed and manipulated with the same syntax. 
Automatically implemented properties takes the UAP to 
the next level, because implementing properties is so easy 
now. Later on automatically implemented properties can 
be "promoted" to full properties in order to add logic to 
setters and getters. 
● The gotcha: Serialization can depend on the names of the 
fields of a type getting serialized (this is esp. true for the 
BinaryFormatter, which is heavily used for .Net Remoting). 
And for automatically implemented properties the name of 
the field may change when the type is modified. So an 
instance's data being serialized in past may no longer 
deserialize successfully later on, if the type has been 
modified in the meantime. Put simple: don't use 
automatically implemented properties in serializable types! 
● Automatically implemented properties are not suitable for 
immutable types as the backing field is always writeable. 
● VB 10 supports auto-implemented properties with default 
values. 
● Also present in Ruby with the attr_accessor generator 
method.
6 
Automatic Properties and Object Initializers in Action 
<InitializerExamples> 
Presents automatically implemented properties and object 
initializers.
7 
Automatically implemented Properties 
// Public property Age in C#1/C#2: 
private int _age; 
public int Age 
{ 
get { return _age; } 
set { _age = value; } 
} 
// New in C#3: Age as automatically implemented property: 
public int Age { get; set; } 
● C#3 allows the definition of properties with a simplified syntax. 
– OK, it can only be used to define simple get/set properties with bare backing fields. 
– A real no-brainer, it; reduces the amount of required code. 
– Idea taken from C++/CLI (trivial properties) and Objective-C (synthesized properties). 
– Gotcha: Automatically implemented properties can break serialization. 
– (Not available for indexers. Default values can't be specified on them explicitly.) 
● In principle field-like events are automatically implemented by default since C#1 
– The methods add and remove and the backing field can be implemented optionally. 
● .Net's properties support the so called Unified Access 
Principle (UAP). UAP means that all the data of an object 
can be accessed and manipulated with the same syntax. 
Automatically implemented properties takes the UAP to 
the next level, because implementing properties is so easy 
now. Later on automatically implemented properties can 
be "promoted" to full properties in order to add logic to 
setters and getters. 
● The gotcha: Serialization can depend on the names of the 
fields of a type getting serialized (this is esp. true for the 
BinaryFormatter, which is heavily used for .Net Remoting). 
And for automatically implemented properties the name of 
the field may change when the type is modified. So an 
instance's data being serialized in past may no longer 
deserialize successfully later on, if the type has been 
modified in the meantime. Put simple: don't use 
automatically implemented properties in serializable types! 
● Automatically implemented properties are not suitable for 
immutable types as the backing field is always writeable. 
● VB 10 supports auto-implemented properties with default 
values. 
● Also present in Ruby with the attr_accessor generator 
method.
8 
Object Initializers 
● Object initializers: simplified initialization of properties during object creation. 
– Create a new object and initialize properties (and fields) with one expression. 
– Reduces the need for a bunch of overloaded ctors and conversion operators. 
– This single expression style supports functional paradigms required for LINQ. 
// Create a Person object and 
// set property Age in C#1/C#2: 
Person p = new Person(); 
p.Age = 42; 
// New equivalent in C#3: Create (dctor) a Person object and 
// set property Age with one expression as object initializer: 
Person p = new Person { Age = 42 }; 
// Our toy: class Person with some properties and ctors: 
public class Person 
{ 
public int Age { get; set; } 
public string Name { get; set; } 
public Person() {} 
public Person(string name) { Name = name; } 
} 
// Create a 2nd Person object, set property Age with an 
// object initializer and set Name with the ctor: 
Person p2 = new Person { Name = "Joe", Age = 32 }; 
/* or: */ Person p3 = new Person("Joe") { Age = 32 }; 
● The individually assigned properties/fields are 
assigned in exactly the order you write them in 
the object initializer. After assigning the last item 
in the object initializer, you are allowed to leave a 
dangling comma. 
● You are not allowed to advise event handlers in 
an object initializer. 
● If an exception is thrown on the initialization of a 
property/field the ctor is called, but the assigned-to 
symbol is only default initialized afterwards (as 
if the exception happened in the ctor). 
● Resources being initialized with object or 
collection initializers within a using-context are 
not exception save (Dispose() won' be called). 
● C++11 introduced uniform initialization, which 
addresses the same idea.
9 
More to come: Embedded Object Initializers 
<InitializerExamples> 
Presents embedded object initializers.
10 
Embedded Object Initializers 
// Let's introduce a new type 'Location': 
public class Location 
{ 
// Just these two properties: 
public string Country { get; set; } 
public string Town { get; set; } 
● Object initializers can be embedded as well. 
– But embedded objects can't be created, only initialized. I.e. Home must be created by Person (the 'new Location()' expression is 
executed in all ctors of Person)! 
// Here is class Person with a property 'Home' of type 'Location': 
public class Person 
{ 
// Field _home is created by all Person's ctors: 
private Location _home = new Location(); 
public Location Home { get { return _home; } } 
// Other properties (Age, Name) and ctors... 
} 
// Create a Person object and apply an object initializer on property Home; 
// initialize Home with an embedded object initializer for type Location: 
Person p = new Person 
{ 
// Apply object initializer in an embedded manner: 
Home = { Country = "US", Town = "Boston" } 
}; 
} 
● The language specification refers to this as 
"setting the properties of an embedded object". 
● Also readonly fields can be initialized like this. 
● The field _home could be created (new 
Location()) by any dedicated ctor as well to be 
functional with embedded object initializers.
11 
Collection Initializers 
<InitializerExamples> 
Presents Collection Initializers.
12 
Hands on Collection Initializers 
// C#2's way to create and fill a List<string>: 
IList<string> names = new List<string>(); 
names.Add("Rose"); 
names.Add("Poppy"); 
names.Add("Daisy"); 
● Remarks on Collection initializers: 
// New in C#3: create (dctor) and initialize a 
// List<string> with a Collection initializer: 
IList<string> names = new List<string> 
{ 
// Calls the method Add(string) for three times. 
"Rose", "Poppy", "Daisy" 
}; 
– They look like array initializer expressions (braced and comma separated value lists). 
– Can be used in concert with any ctor of the Collection to be initialized. 
– Can be used locally or for initialization of members. 
– Render the construction and initialization of a Collection into one expression. 
● A Collection must fulfill some requirements to be used with Collection initializers: 
– The Collection must implement IEnumerable or IEnumerable<T>. 
– The Collection must provide any public overload (any signature) of method Add(). 
● After assigning the last item of the anonymous 
type, you are allowed to leave a dangling comma 
(you can also leave it on arrays). 
● In Objective-C there are so called container 
literals, which solve the same problem like C#'s 
Collection initializers.
13 
More Collection Initializers and implicitly typed Arrays 
<InitializerExamples> 
Presents more Collection initializers and implicitly typed arrays.
14 
More on Collection Initializers and implicitly typed Arrays 
// Apply a Collection initializer on a Dictionary<string, int> in C#3: 
IDictionary<string, int> nameToAge = new Dictionary<string, int> 
{ 
// Calls the method Add(string, int) for three times. 
{"Rose", 31}, {"Poppy", 32}, {"Daisy", 24} 
}; 
● Any public overload of method Add() can be used to initialize Collections. 
– Additionally the Collection initializers can be used as embedded object initializers! 
// Assume we have a method with a string-array parameter: 
private void AwaitsAStringArray(string[] strings); 
// Pass a newly created array with an array initializer in C#1/2: 
AwaitsAStringArray(new string[] { "Monica", "Rebecca", "Lydia" }); 
// New in C#3: leave the type name away on the new keyword: 
AwaitsAStringArray(new[] { "Monica", "Rebecca", "Lydia" }); 
● This is a syntactic simplification, which is handy on passing arrays to methods. 
– In C#3 there exist situations, in which static types are unknown or anonymous. 
– Only allowed, if the initial array items can be implicitly converted to the same type. 
● Under certain circumstances implicitly typed 
arrays can be initialized with initializer lists having 
mixed static types of their items: 
● There must be one type into which all the 
initializer items can be converted to implicitly. 
● Only the static types of initializer items' 
expressions are considered for this conversion. 
● If these bullets do not meet, or if all the 
initializer items are typeless expressions (null 
literals or anonymous methods with no casts) 
the array initializer will fail to compile.
15 
What is the Sense of these Features? 
● Removal of syntactical fluff. 
– There are many developers that longed for these simplifications. 
– Programmatic "creation" of test data is much simpler now. 
– Once again: functional, "one-expression"- programming style is possible. 
● Why is the functional style preferred? 
– Syntactically concise. 
– Contributes to LINQ's expressiveness. 
● Simplified initialization is the basis of the so-called "anonymous types" in C#3. 
– More to come in next lectures...
16 
Thank you!

Recommandé

New c sharp3_features_(linq)_part_i par
New c sharp3_features_(linq)_part_iNew c sharp3_features_(linq)_part_i
New c sharp3_features_(linq)_part_iNico Ludwig
240 vues16 diapositives
Oop Constructor Destructors Constructor Overloading lecture 2 par
Oop Constructor  Destructors Constructor Overloading lecture 2Oop Constructor  Destructors Constructor Overloading lecture 2
Oop Constructor Destructors Constructor Overloading lecture 2Abbas Ajmal
993 vues24 diapositives
ADG Poznań - Kotlin for Android developers par
ADG Poznań - Kotlin for Android developersADG Poznań - Kotlin for Android developers
ADG Poznań - Kotlin for Android developersBartosz Kosarzycki
2.5K vues51 diapositives
JavaScript in 2016 par
JavaScript in 2016JavaScript in 2016
JavaScript in 2016Codemotion
636 vues65 diapositives
Advanced javascript par
Advanced javascriptAdvanced javascript
Advanced javascriptDoeun KOCH
487 vues56 diapositives
Kotlin in action par
Kotlin in actionKotlin in action
Kotlin in actionCiro Rizzo
3.7K vues26 diapositives

Contenu connexe

Tendances

Object Oriented Programming in JavaScript par
Object Oriented Programming in JavaScriptObject Oriented Programming in JavaScript
Object Oriented Programming in JavaScriptzand3rs
1.5K vues30 diapositives
Advanced JavaScript par
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScriptFu Cheng
1.6K vues41 diapositives
Kotlin Developer Starter in Android projects par
Kotlin Developer Starter in Android projectsKotlin Developer Starter in Android projects
Kotlin Developer Starter in Android projectsBartosz Kosarzycki
5.1K vues29 diapositives
Kotlin cheat sheet by ekito par
Kotlin cheat sheet by ekitoKotlin cheat sheet by ekito
Kotlin cheat sheet by ekitoArnaud Giuliani
2.3K vues2 diapositives
Advanced JavaScript par
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScriptStoyan Stefanov
4K vues113 diapositives
Memory management in c++ par
Memory management in c++Memory management in c++
Memory management in c++Syed Hassan Kazmi
255 vues5 diapositives

Tendances(20)

Object Oriented Programming in JavaScript par zand3rs
Object Oriented Programming in JavaScriptObject Oriented Programming in JavaScript
Object Oriented Programming in JavaScript
zand3rs1.5K vues
Advanced JavaScript par Fu Cheng
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
Fu Cheng1.6K vues
Memory Management with Java and C++ par Mohammad Shaker
Memory Management with Java and C++Memory Management with Java and C++
Memory Management with Java and C++
Mohammad Shaker2.5K vues
Kotlin hands on - MorningTech ekito 2017 par Arnaud Giuliani
Kotlin hands on - MorningTech ekito 2017Kotlin hands on - MorningTech ekito 2017
Kotlin hands on - MorningTech ekito 2017
Arnaud Giuliani476 vues
Functional Programming in Scala: Notes par Roberto Casadei
Functional Programming in Scala: NotesFunctional Programming in Scala: Notes
Functional Programming in Scala: Notes
Roberto Casadei1.6K vues
Develop your next app with kotlin @ AndroidMakersFr 2017 par Arnaud Giuliani
Develop your next app with kotlin @ AndroidMakersFr 2017Develop your next app with kotlin @ AndroidMakersFr 2017
Develop your next app with kotlin @ AndroidMakersFr 2017
Arnaud Giuliani3.2K vues
The Kotlin Programming Language, Svetlana Isakova par Vasil Remeniuk
The Kotlin Programming Language, Svetlana IsakovaThe Kotlin Programming Language, Svetlana Isakova
The Kotlin Programming Language, Svetlana Isakova
Vasil Remeniuk3.4K vues
Kotlin, smarter development for the jvm par Arnaud Giuliani
Kotlin, smarter development for the jvmKotlin, smarter development for the jvm
Kotlin, smarter development for the jvm
Arnaud Giuliani898 vues
Reactive Programming with JavaScript par Codemotion
Reactive Programming with JavaScriptReactive Programming with JavaScript
Reactive Programming with JavaScript
Codemotion1.1K vues
Kotlin advanced - language reference for android developers par Bartosz Kosarzycki
Kotlin advanced - language reference for android developersKotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developers
Bartosz Kosarzycki5.7K vues

En vedette

Programme de la_coupe_de_polynesie par
Programme de la_coupe_de_polynesieProgramme de la_coupe_de_polynesie
Programme de la_coupe_de_polynesieLaurent BUVRY
363 vues13 diapositives
In style front cover par
In style front coverIn style front cover
In style front coverrebbeccakennon
238 vues2 diapositives
Fdi Effects In Bulgaria, Croatia, Egypt, Morocco par
Fdi Effects In Bulgaria, Croatia, Egypt, MoroccoFdi Effects In Bulgaria, Croatia, Egypt, Morocco
Fdi Effects In Bulgaria, Croatia, Egypt, MoroccoZach Thompson
584 vues32 diapositives
Muskan city homes is a real estate consultant par
Muskan city homes is a real estate consultantMuskan city homes is a real estate consultant
Muskan city homes is a real estate consultantKalendra Kumar
82 vues1 diapositive
Possible models5 par
Possible models5Possible models5
Possible models5rebbeccakennon
264 vues7 diapositives
Fortune Fort Hyderabad par
Fortune Fort HyderabadFortune Fort Hyderabad
Fortune Fort Hyderabadravikumar9740
203 vues9 diapositives

Similaire à New c sharp3_features_(linq)_part_i

New microsoft office word document (2) par
New microsoft office word document (2)New microsoft office word document (2)
New microsoft office word document (2)rashmita_mishra
1.6K vues48 diapositives
C questions par
C questionsC questions
C questionsparm112
853 vues15 diapositives
(4) c sharp introduction_object_orientation_part_i par
(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
147 vues21 diapositives
Design patterns in javascript par
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascriptAyush Sharma
125 vues60 diapositives
Exploring Kotlin language basics for Android App development par
Exploring Kotlin language basics for Android App developmentExploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App developmentJayaprakash R
101 vues41 diapositives
Uncommon Design Patterns par
Uncommon Design PatternsUncommon Design Patterns
Uncommon Design PatternsStefano Fago
3K vues23 diapositives

Similaire à New c sharp3_features_(linq)_part_i(20)

New microsoft office word document (2) par rashmita_mishra
New microsoft office word document (2)New microsoft office word document (2)
New microsoft office word document (2)
rashmita_mishra1.6K vues
C questions par parm112
C questionsC questions
C questions
parm112853 vues
(4) c sharp introduction_object_orientation_part_i par Nico Ludwig
(4) c sharp introduction_object_orientation_part_i(4) c sharp introduction_object_orientation_part_i
(4) c sharp introduction_object_orientation_part_i
Nico Ludwig147 vues
Design patterns in javascript par Ayush Sharma
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascript
Ayush Sharma125 vues
Exploring Kotlin language basics for Android App development par Jayaprakash R
Exploring Kotlin language basics for Android App developmentExploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App development
Jayaprakash R101 vues
Effective Java. By materials of Josch Bloch's book par Roman Tsypuk
Effective Java. By materials of Josch Bloch's bookEffective Java. By materials of Josch Bloch's book
Effective Java. By materials of Josch Bloch's book
Roman Tsypuk75 vues
C, C++ Interview Questions Part - 1 par ReKruiTIn.com
C, C++ Interview Questions Part - 1C, C++ Interview Questions Part - 1
C, C++ Interview Questions Part - 1
ReKruiTIn.com16.8K vues
computer notes - Reference variables ii par ecomputernotes
computer notes - Reference variables iicomputer notes - Reference variables ii
computer notes - Reference variables ii
ecomputernotes329 vues
Review of c_sharp2_features_part_iii par Nico Ludwig
Review of c_sharp2_features_part_iiiReview of c_sharp2_features_part_iii
Review of c_sharp2_features_part_iii
Nico Ludwig202 vues
(4) cpp abstractions references_copies_and_const-ness par Nico Ludwig
(4) cpp abstractions references_copies_and_const-ness(4) cpp abstractions references_copies_and_const-ness
(4) cpp abstractions references_copies_and_const-ness
Nico Ludwig162 vues
C++ questions And Answer par lavparmar007
C++ questions And AnswerC++ questions And Answer
C++ questions And Answer
lavparmar00716.6K vues
Constructors & Destructors [Compatibility Mode].pdf par LadallaRajKumar
Constructors & Destructors [Compatibility Mode].pdfConstructors & Destructors [Compatibility Mode].pdf
Constructors & Destructors [Compatibility Mode].pdf
Introduction to Koltin for Android Part I par Atif AbbAsi
Introduction to Koltin for Android Part I Introduction to Koltin for Android Part I
Introduction to Koltin for Android Part I
Atif AbbAsi1.2K vues
eXo SEA - JavaScript Introduction Training par Hoat Le
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction Training
Hoat Le1.7K vues
(3) cpp abstractions more_on_user_defined_types par Nico Ludwig
(3) cpp abstractions more_on_user_defined_types(3) cpp abstractions more_on_user_defined_types
(3) cpp abstractions more_on_user_defined_types
Nico Ludwig292 vues

Plus de Nico Ludwig

Grundkurs fuer excel_part_v par
Grundkurs fuer excel_part_vGrundkurs fuer excel_part_v
Grundkurs fuer excel_part_vNico Ludwig
522 vues21 diapositives
Grundkurs fuer excel_part_iv par
Grundkurs fuer excel_part_ivGrundkurs fuer excel_part_iv
Grundkurs fuer excel_part_ivNico Ludwig
400 vues18 diapositives
Grundkurs fuer excel_part_iii par
Grundkurs fuer excel_part_iiiGrundkurs fuer excel_part_iii
Grundkurs fuer excel_part_iiiNico Ludwig
772 vues26 diapositives
Grundkurs fuer excel_part_ii par
Grundkurs fuer excel_part_iiGrundkurs fuer excel_part_ii
Grundkurs fuer excel_part_iiNico Ludwig
916 vues36 diapositives
Grundkurs fuer excel_part_i par
Grundkurs fuer excel_part_iGrundkurs fuer excel_part_i
Grundkurs fuer excel_part_iNico Ludwig
538 vues26 diapositives
(2) gui drawing par
(2) gui drawing(2) gui drawing
(2) gui drawingNico Ludwig
419 vues27 diapositives

Plus de Nico Ludwig(20)

Grundkurs fuer excel_part_v par Nico Ludwig
Grundkurs fuer excel_part_vGrundkurs fuer excel_part_v
Grundkurs fuer excel_part_v
Nico Ludwig522 vues
Grundkurs fuer excel_part_iv par Nico Ludwig
Grundkurs fuer excel_part_ivGrundkurs fuer excel_part_iv
Grundkurs fuer excel_part_iv
Nico Ludwig400 vues
Grundkurs fuer excel_part_iii par Nico Ludwig
Grundkurs fuer excel_part_iiiGrundkurs fuer excel_part_iii
Grundkurs fuer excel_part_iii
Nico Ludwig772 vues
Grundkurs fuer excel_part_ii par Nico Ludwig
Grundkurs fuer excel_part_iiGrundkurs fuer excel_part_ii
Grundkurs fuer excel_part_ii
Nico Ludwig916 vues
Grundkurs fuer excel_part_i par Nico Ludwig
Grundkurs fuer excel_part_iGrundkurs fuer excel_part_i
Grundkurs fuer excel_part_i
Nico Ludwig538 vues
(1) gui history_of_interactivity par Nico Ludwig
(1) gui history_of_interactivity(1) gui history_of_interactivity
(1) gui history_of_interactivity
Nico Ludwig461 vues
(1) gui history_of_interactivity par Nico Ludwig
(1) gui history_of_interactivity(1) gui history_of_interactivity
(1) gui history_of_interactivity
Nico Ludwig339 vues
New c sharp4_features_part_vi par Nico Ludwig
New c sharp4_features_part_viNew c sharp4_features_part_vi
New c sharp4_features_part_vi
Nico Ludwig391 vues
New c sharp4_features_part_v par Nico Ludwig
New c sharp4_features_part_vNew c sharp4_features_part_v
New c sharp4_features_part_v
Nico Ludwig255 vues
New c sharp4_features_part_iv par Nico Ludwig
New c sharp4_features_part_ivNew c sharp4_features_part_iv
New c sharp4_features_part_iv
Nico Ludwig326 vues
New c sharp4_features_part_iii par Nico Ludwig
New c sharp4_features_part_iiiNew c sharp4_features_part_iii
New c sharp4_features_part_iii
Nico Ludwig237 vues
New c sharp4_features_part_ii par Nico Ludwig
New c sharp4_features_part_iiNew c sharp4_features_part_ii
New c sharp4_features_part_ii
Nico Ludwig261 vues
New c sharp4_features_part_i par Nico Ludwig
New c sharp4_features_part_iNew c sharp4_features_part_i
New c sharp4_features_part_i
Nico Ludwig235 vues
New c sharp3_features_(linq)_part_v par Nico Ludwig
New c sharp3_features_(linq)_part_vNew c sharp3_features_(linq)_part_v
New c sharp3_features_(linq)_part_v
Nico Ludwig252 vues
New c sharp3_features_(linq)_part_iv par Nico Ludwig
New c sharp3_features_(linq)_part_ivNew c sharp3_features_(linq)_part_iv
New c sharp3_features_(linq)_part_iv
Nico Ludwig235 vues
New c sharp3_features_(linq)_part_iv par Nico Ludwig
New c sharp3_features_(linq)_part_ivNew c sharp3_features_(linq)_part_iv
New c sharp3_features_(linq)_part_iv
Nico Ludwig190 vues
New c sharp3_features_(linq)_part_iii par Nico Ludwig
New c sharp3_features_(linq)_part_iiiNew c sharp3_features_(linq)_part_iii
New c sharp3_features_(linq)_part_iii
Nico Ludwig258 vues
New c sharp3_features_(linq)_part_ii par Nico Ludwig
New c sharp3_features_(linq)_part_iiNew c sharp3_features_(linq)_part_ii
New c sharp3_features_(linq)_part_ii
Nico Ludwig197 vues

New c sharp3_features_(linq)_part_i

  • 1. 1 New C#3 Features (LINQ) – Part I Nico Ludwig (@ersatzteilchen)
  • 2. 2 TOC ● New C#3 Features – Part I – Focus of C#3 Features – Automatically implemented Properties – Object and Collection Initializers: new Ways to initialize Objects and Collections ● Sources: – Jon Skeet, CSharp in Depth
  • 3. 3 Changes in .Net 3/3.5 – Overview ● .Net 3/3.5 runtime – All the .Net 3 and 3.5 features are based on .Net 2 features. – The CLR wasn't even changed, .Net 3.5 still uses a CLR 2 underneath. ● .Net 3/3.5 libraries – Some new libraries have been added: ● Windows Presentation Foundation (WPF) ● Windows Communication Foundation (WCF) ● Windows Workflow Foundation (WF) ● Windows CardSpace – Some present APIs have been extended. ● C#3 and VB9 got syntactical enhancements to cope with LINQ. – The compilers have been updated, but no changes to the CIL have been done. ● Windows CardSpace is a system to manage different identities against other environments, e.g. web sites. CardSpace is like your wallet with different cards representing different identities.
  • 4. 4 Which Aims does C#3 pursue? ● Focus of C#3 features: – Enhance readability and reduce syntactic fluff. – Increase productivity: "less code that monkeys could write". – More expressiveness to support a functional programming style. – LINQ ● C#3 requires the .Net 3.5 being installed at minimum. – As well as Visual Studio 2008 or newer for development. ● In this presentation: – The new boilerplate features of C#3 will be examined.
  • 5. 5 Automatically implemented Properties // Public property Age in C#1/C#2: private int _age; public int Age { get { return _age; } set { _age = value; } } // New in C#3: Age as automatically implemented property: public int Age { get; set; } ● C#3 allows the definition of properties with a simplified syntax. – OK, it can only be used to define simple get/set properties with bare backing fields. – A real no-brainer, it; reduces the amount of required code. – Idea taken from C++/CLI (trivial properties) and Objective-C (synthesized properties). – Gotcha: Automatically implemented properties can break serialization. – (Not available for indexers. Default values can't be specified on them explicitly.) ● In principle field-like events are automatically implemented by default since C#1 – The methods add and remove and the backing field can be implemented optionally. ● .Net's properties support the so called Unified Access Principle (UAP). UAP means that all the data of an object can be accessed and manipulated with the same syntax. Automatically implemented properties takes the UAP to the next level, because implementing properties is so easy now. Later on automatically implemented properties can be "promoted" to full properties in order to add logic to setters and getters. ● The gotcha: Serialization can depend on the names of the fields of a type getting serialized (this is esp. true for the BinaryFormatter, which is heavily used for .Net Remoting). And for automatically implemented properties the name of the field may change when the type is modified. So an instance's data being serialized in past may no longer deserialize successfully later on, if the type has been modified in the meantime. Put simple: don't use automatically implemented properties in serializable types! ● Automatically implemented properties are not suitable for immutable types as the backing field is always writeable. ● VB 10 supports auto-implemented properties with default values. ● Also present in Ruby with the attr_accessor generator method.
  • 6. 6 Automatic Properties and Object Initializers in Action <InitializerExamples> Presents automatically implemented properties and object initializers.
  • 7. 7 Automatically implemented Properties // Public property Age in C#1/C#2: private int _age; public int Age { get { return _age; } set { _age = value; } } // New in C#3: Age as automatically implemented property: public int Age { get; set; } ● C#3 allows the definition of properties with a simplified syntax. – OK, it can only be used to define simple get/set properties with bare backing fields. – A real no-brainer, it; reduces the amount of required code. – Idea taken from C++/CLI (trivial properties) and Objective-C (synthesized properties). – Gotcha: Automatically implemented properties can break serialization. – (Not available for indexers. Default values can't be specified on them explicitly.) ● In principle field-like events are automatically implemented by default since C#1 – The methods add and remove and the backing field can be implemented optionally. ● .Net's properties support the so called Unified Access Principle (UAP). UAP means that all the data of an object can be accessed and manipulated with the same syntax. Automatically implemented properties takes the UAP to the next level, because implementing properties is so easy now. Later on automatically implemented properties can be "promoted" to full properties in order to add logic to setters and getters. ● The gotcha: Serialization can depend on the names of the fields of a type getting serialized (this is esp. true for the BinaryFormatter, which is heavily used for .Net Remoting). And for automatically implemented properties the name of the field may change when the type is modified. So an instance's data being serialized in past may no longer deserialize successfully later on, if the type has been modified in the meantime. Put simple: don't use automatically implemented properties in serializable types! ● Automatically implemented properties are not suitable for immutable types as the backing field is always writeable. ● VB 10 supports auto-implemented properties with default values. ● Also present in Ruby with the attr_accessor generator method.
  • 8. 8 Object Initializers ● Object initializers: simplified initialization of properties during object creation. – Create a new object and initialize properties (and fields) with one expression. – Reduces the need for a bunch of overloaded ctors and conversion operators. – This single expression style supports functional paradigms required for LINQ. // Create a Person object and // set property Age in C#1/C#2: Person p = new Person(); p.Age = 42; // New equivalent in C#3: Create (dctor) a Person object and // set property Age with one expression as object initializer: Person p = new Person { Age = 42 }; // Our toy: class Person with some properties and ctors: public class Person { public int Age { get; set; } public string Name { get; set; } public Person() {} public Person(string name) { Name = name; } } // Create a 2nd Person object, set property Age with an // object initializer and set Name with the ctor: Person p2 = new Person { Name = "Joe", Age = 32 }; /* or: */ Person p3 = new Person("Joe") { Age = 32 }; ● The individually assigned properties/fields are assigned in exactly the order you write them in the object initializer. After assigning the last item in the object initializer, you are allowed to leave a dangling comma. ● You are not allowed to advise event handlers in an object initializer. ● If an exception is thrown on the initialization of a property/field the ctor is called, but the assigned-to symbol is only default initialized afterwards (as if the exception happened in the ctor). ● Resources being initialized with object or collection initializers within a using-context are not exception save (Dispose() won' be called). ● C++11 introduced uniform initialization, which addresses the same idea.
  • 9. 9 More to come: Embedded Object Initializers <InitializerExamples> Presents embedded object initializers.
  • 10. 10 Embedded Object Initializers // Let's introduce a new type 'Location': public class Location { // Just these two properties: public string Country { get; set; } public string Town { get; set; } ● Object initializers can be embedded as well. – But embedded objects can't be created, only initialized. I.e. Home must be created by Person (the 'new Location()' expression is executed in all ctors of Person)! // Here is class Person with a property 'Home' of type 'Location': public class Person { // Field _home is created by all Person's ctors: private Location _home = new Location(); public Location Home { get { return _home; } } // Other properties (Age, Name) and ctors... } // Create a Person object and apply an object initializer on property Home; // initialize Home with an embedded object initializer for type Location: Person p = new Person { // Apply object initializer in an embedded manner: Home = { Country = "US", Town = "Boston" } }; } ● The language specification refers to this as "setting the properties of an embedded object". ● Also readonly fields can be initialized like this. ● The field _home could be created (new Location()) by any dedicated ctor as well to be functional with embedded object initializers.
  • 11. 11 Collection Initializers <InitializerExamples> Presents Collection Initializers.
  • 12. 12 Hands on Collection Initializers // C#2's way to create and fill a List<string>: IList<string> names = new List<string>(); names.Add("Rose"); names.Add("Poppy"); names.Add("Daisy"); ● Remarks on Collection initializers: // New in C#3: create (dctor) and initialize a // List<string> with a Collection initializer: IList<string> names = new List<string> { // Calls the method Add(string) for three times. "Rose", "Poppy", "Daisy" }; – They look like array initializer expressions (braced and comma separated value lists). – Can be used in concert with any ctor of the Collection to be initialized. – Can be used locally or for initialization of members. – Render the construction and initialization of a Collection into one expression. ● A Collection must fulfill some requirements to be used with Collection initializers: – The Collection must implement IEnumerable or IEnumerable<T>. – The Collection must provide any public overload (any signature) of method Add(). ● After assigning the last item of the anonymous type, you are allowed to leave a dangling comma (you can also leave it on arrays). ● In Objective-C there are so called container literals, which solve the same problem like C#'s Collection initializers.
  • 13. 13 More Collection Initializers and implicitly typed Arrays <InitializerExamples> Presents more Collection initializers and implicitly typed arrays.
  • 14. 14 More on Collection Initializers and implicitly typed Arrays // Apply a Collection initializer on a Dictionary<string, int> in C#3: IDictionary<string, int> nameToAge = new Dictionary<string, int> { // Calls the method Add(string, int) for three times. {"Rose", 31}, {"Poppy", 32}, {"Daisy", 24} }; ● Any public overload of method Add() can be used to initialize Collections. – Additionally the Collection initializers can be used as embedded object initializers! // Assume we have a method with a string-array parameter: private void AwaitsAStringArray(string[] strings); // Pass a newly created array with an array initializer in C#1/2: AwaitsAStringArray(new string[] { "Monica", "Rebecca", "Lydia" }); // New in C#3: leave the type name away on the new keyword: AwaitsAStringArray(new[] { "Monica", "Rebecca", "Lydia" }); ● This is a syntactic simplification, which is handy on passing arrays to methods. – In C#3 there exist situations, in which static types are unknown or anonymous. – Only allowed, if the initial array items can be implicitly converted to the same type. ● Under certain circumstances implicitly typed arrays can be initialized with initializer lists having mixed static types of their items: ● There must be one type into which all the initializer items can be converted to implicitly. ● Only the static types of initializer items' expressions are considered for this conversion. ● If these bullets do not meet, or if all the initializer items are typeless expressions (null literals or anonymous methods with no casts) the array initializer will fail to compile.
  • 15. 15 What is the Sense of these Features? ● Removal of syntactical fluff. – There are many developers that longed for these simplifications. – Programmatic "creation" of test data is much simpler now. – Once again: functional, "one-expression"- programming style is possible. ● Why is the functional style preferred? – Syntactically concise. – Contributes to LINQ's expressiveness. ● Simplified initialization is the basis of the so-called "anonymous types" in C#3. – More to come in next lectures...