SlideShare une entreprise Scribd logo
1  sur  48
What's New In C# 4.0
Paulo Morgado
The Evolution Of C# Covariance And Contravariance Named And Optional Arguments Dynamic Programming COM Interop Improvements Agenda
The Evolution Of C#
The Evolution Of C#
Trends
Dynamic vs. Static
VB ,[object Object]
Optional Arguments
Index Properties (COM)
Lambda Statements
Auto-Implemented Properties
Colection InitializersC# C# VB Co-Evolution
The Evolution Of C#
The Evolution Of C# http://paulomorgado.net/en/blog/archive/2010/04/12/the-evolution-of-c.aspx Resources
Covariance And Contravariance
In multilinear algebra and tensor analysis, covariance and contravariance describe how the quantitative description of certain geometrical or physical entities changes when passing from one coordinate system to another. Wikipedia Covariance And Contravarance
Type Tis greater than (>) type Sif Sis a subtype of (derives from) T Covariance And Contravarance T≥S typeof(T).IsAssignableFrom(typeof(S))
Give 2 types Base and Derived, such that: There is a reference (or identity) conversion between Base and Derived Base ≥ Derived A generic type definition Generic<T> is: Covariant in T If Genérico<Base> ≥ Genérico<Derived> Contravariant in T If Genérico<Base> ≤ Genérico<Derived> Invariant in T If neither of the above apply Covariance And Contravarance
Contravariante em T Covariante em T typeof(Base).IsAssignableFrom(typeof(Derived)) typeof(Base).IsAssignableFrom(typeof(Derived)) typeof(G<Derived>).IsAssignableFrom(typeof(G<Base>)) typeof(G<Base>).IsAssignableFrom(typeof(G<Derived>)) Covariance And Contravarance
Covariance And Contravarance C# (.NET) arrays are covariant string[] strings = GetStringArray(); Process(strings); … but not safely covariant void Process(object[] objects) { … } void Process(object[] objects) {    objects[0] = "Hello";       // Ok    objects[1] = newButton();  // Exception! }
Covariance And Contravarance Until now, C# (.NET) generics have been invariant List<string> strings = GetStringList(); Process(strings); C# 4.0 supports safe covariance and contravariance void Process(IEnumerable<object> objects) { // IEnumerable<T> is read-only and // therefore safely covariant } void Process(IEnumerable<object> objects) { … }
Safe Covariance out= covariant Output positions only publicinterfaceIEnumerable<T> { IEnumerator<T> GetEnumerator(); } publicinterfaceIEnumerable<out T> { IEnumerator<T> GetEnumerator(); } Can be treated as less derived publicinterfaceIEnumerator<T> {    T Current { get; } boolMoveNext(); } publicinterfaceIEnumerator<out T> {    T Current { get; } boolMoveNext(); } IEnumerable<string> strings = GetStrings(); IEnumerable<object> objects = strings;
Safe Contravariance in= contravariantInput positions only Can be treated as more derived publicinterfaceIComparer<T> { int Compare(T x, T y); } publicinterfaceIComparer<in T> { int Compare(T x, T y); } IComparer<object> objComp = GetComparer(); IComparer<string> strComp = objComp;
Supported for generic interface and delegate types only. Verified/enforced staticaliy in the definition. Value types are always invariant IEnumerable<int> is not IEnumerable<object> Similar to existing rules for arrays ref and out parameters need invariant types Variance In C# 4.o
Variance In .NET 4.0
Covariance And Contravariance In Generics http://paulomorgado.net/en/blog/archive/2010/04/13/c-4-0-covariance-and-contravariance-in-generics.aspx Covariance And Contravariance In Generics Made Easy http://paulomorgado.net/en/blog/archive/2010/04/15/c-4-0-covariance-and-contravariance-in-generics-made-easy.aspx Covarince and Contravariance in Generics http://msdn.microsoft.com/library/dd799517(VS.100).aspx Exact rules for variance validity http://blogs.msdn.com/ericlippert/archive/2009/12/03/exact-rules-for-variância-validity.aspx Events get a little overhaul in C# 4, Afterward: Effective Events http://blogs.msdn.com/cburrows/archive/2010/03/30/events-get-a-little-overhaul-in-c-4-afterward-effective-events.aspx Resources
Named And Optional Arguments
Named And Optional Arguments Greeting("Mr.", "Morgado", 42); Parameters Arguments public void Greeting(string title, string name, intage) They always have names They are never optional
Named Arguments int i = 0; Method(i, third: i++, second: ++i); int i = 0; int CS$0$0000 = i++; int CS$0$0001 = ++i; Method(i, CS$0$0001, CS$0$0000);  public void Method(intfirst, intsecond, intthird)
Optional Arguments int i = 0; Method(i, third: ++i); int i = 0; int CS$0$0000 = ++i; Method(i, 2, CS$0$0000);  public void Method(intfirst, intsecond = 5, intthird = 6)  public void Method(intfirst, intsecond = 2, intthird = 3)  public void Method(intfirst, intsecond)  They look like overloads. But they aren’t! public void Method(intfirst)
Argument Classes Optional Arguments - Alternative XmlReaderSettings settings = newXmlReaderSettings(); settings.ValidationType = ValidationType.Auto; XmlReader.Create("file.xml", settings); XmlReader.Create( "file.xml", new { ValidationType = ValidationType.Auto }); XmlReader.Create( "file.xml", newXmlReaderSettings { ValidationType = ValidationType.Auto }); Not yet!
C# 4.0: Named And Optional Arguments http://paulomorgado.net/en/blog/archive/2010/04/16/c-4-0-named-and-optional-arguments.aspx C# 4.0: Alternative To Optional Arguments http://paulomorgado.net/en/blog/archive/2010/04/18/c-4-0-alternative-to-optional-arguments.aspx Named and Optional Arguments (C# Programming Guide) http://msdn.microsoft.com/library/dd264739(VS.100).aspx Resources
Dynamic Programming
Dynamic Language Runtime IronPython IronRuby C# VB.NET Others… Dynamic Language Runtime Expression Trees Dynamic Dispatch Call Site Caching PythonBinder RubyBinder COMBinder JavaScriptBinder ObjectBinder
Objectos Tipados Dinâmicamente Calculatorcalculator = GetCalculator(); int sum = calc.Add(10, 20); object calculator = GetCalculator(); Type calculatorType = calculator.GetType(); object res = calculatorType.InvokeMember("Add", BindingFlags.InvokeMethod, null,     calculator, newobject[] { 10, 20 }); int sum = Convert.ToInt32(res); ScriptObject calculator = GetCalculator(); object res = calculator.Invoke("Add", 10, 20); int sum = Convert.ToInt32(res); Statically typed to be dynamic dynamic calc = GetCalculator(); int sum = calc.Add(10, 20); Dynamic method invocation Dynamic conversion
Dynamically Typed Objects Compile-time typedynamic Run-time typeSystem.Int32 dynamic x = 1; dynamic y = "Hello"; dynamic z = newList<int> { 1, 2, 3 }; When operand(s) are dynamic: ,[object Object]
At run-time, actual type(s) substituted for dynamic
Static result type of operation is dynamic,[object Object]
IDynamicMetaObjectProvider Represents a dynamic object that can have operations determined at run-time. DynamicObject : IDynamicMetaObjectProvider Enables you to define which operations can be performed on dynamic objects and how to perform those operations. ExpandoObject : IDynamicMetaObjectProvider Enables you to add and delete members of its instances at run time and also to set and get values of these members. Building Dynamic Objects
Dynamic Programming http://paulomorgado.net/en/blog/archive/2010/04/18/c-4-0-dynamic-programming.aspx C# Proposal: Compile Time Static Checking Of Dynamic Objects http://paulomorgado.net/en/blog/archive/2010/03/19/c-proposal-compile-time-static-checking-of-dynamic-objects.aspx Using Type dynamic (C# Programming Guide) http://msdn.microsoft.com/library/dd264736(VS.100).aspx Dynamic Language Runtime Overview http://msdn.microsoft.com/library/dd233052(v=VS.100).aspx Resources
COM Interop Improvements
Named and optional arguments Ommiting ref Dynamic Import Automatic mapping object -> dynamic Indexed properties Type Equivalence And Type Embedding (“NO PIA”) COM Interop Improvements
Ommiting ref objectfileName = "Test.docx"; object missing  = Missing.Value; document.SaveAs(reffileName, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); document.SaveAs("Test.docx", Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value); document.SaveAs("Test.docx");
Dynamic Import ((Excel.Range)(excel.Cells[1, 1])).Value2 = "Hello World!"; excel.Cells[1, 1] = "Hello World!";  Excel.Range range = (Excel.Range)(excel.Cells[1, 1]);  Excel.Rangerange = excel.Cells[1, 1];
Type Equivalence And Type Embedding (NO PIA)
COM Interop Improvements http://paulomorgado.net/en/blog/archive/2010/04/19/c-4-0-com-interop-improvements.aspx Type Equivalence and Embedded InteropTypes http://msdn.microsoft.com/library/dd997297.aspx Resources
Demos

Contenu connexe

Tendances

Solid C++ by Example
Solid C++ by ExampleSolid C++ by Example
Solid C++ by ExampleOlve Maudal
 
Gentle introduction to modern C++
Gentle introduction to modern C++Gentle introduction to modern C++
Gentle introduction to modern C++Mihai Todor
 
C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)Olve Maudal
 
[C++ Korea] Effective Modern C++ Study, Item 11 - 13
[C++ Korea] Effective Modern C++ Study, Item 11 - 13[C++ Korea] Effective Modern C++ Study, Item 11 - 13
[C++ Korea] Effective Modern C++ Study, Item 11 - 13Chris Ohk
 
#OOP_D_ITS - 4th - C++ Oop And Class Structure
#OOP_D_ITS - 4th - C++ Oop And Class Structure#OOP_D_ITS - 4th - C++ Oop And Class Structure
#OOP_D_ITS - 4th - C++ Oop And Class StructureHadziq Fabroyir
 
Paradigmas de Linguagens de Programacao - Aula #4
Paradigmas de Linguagens de Programacao - Aula #4Paradigmas de Linguagens de Programacao - Aula #4
Paradigmas de Linguagens de Programacao - Aula #4Ismar Silveira
 
Constructors and destructors in C++
Constructors and destructors in  C++Constructors and destructors in  C++
Constructors and destructors in C++RAJ KUMAR
 
Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014
Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014
Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014Susan Potter
 
Fun with Lambdas: C++14 Style (part 2)
Fun with Lambdas: C++14 Style (part 2)Fun with Lambdas: C++14 Style (part 2)
Fun with Lambdas: C++14 Style (part 2)Sumant Tambe
 
Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Scott Wlaschin
 

Tendances (20)

C++ programming
C++ programmingC++ programming
C++ programming
 
C# 6.0 Preview
C# 6.0 PreviewC# 6.0 Preview
C# 6.0 Preview
 
Solid C++ by Example
Solid C++ by ExampleSolid C++ by Example
Solid C++ by Example
 
Gentle introduction to modern C++
Gentle introduction to modern C++Gentle introduction to modern C++
Gentle introduction to modern C++
 
Summary of C++17 features
Summary of C++17 featuresSummary of C++17 features
Summary of C++17 features
 
A Taste of Dotty
A Taste of DottyA Taste of Dotty
A Taste of Dotty
 
Smart pointers
Smart pointersSmart pointers
Smart pointers
 
C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)
 
[C++ Korea] Effective Modern C++ Study, Item 11 - 13
[C++ Korea] Effective Modern C++ Study, Item 11 - 13[C++ Korea] Effective Modern C++ Study, Item 11 - 13
[C++ Korea] Effective Modern C++ Study, Item 11 - 13
 
#OOP_D_ITS - 4th - C++ Oop And Class Structure
#OOP_D_ITS - 4th - C++ Oop And Class Structure#OOP_D_ITS - 4th - C++ Oop And Class Structure
#OOP_D_ITS - 4th - C++ Oop And Class Structure
 
C++11
C++11C++11
C++11
 
Paradigmas de Linguagens de Programacao - Aula #4
Paradigmas de Linguagens de Programacao - Aula #4Paradigmas de Linguagens de Programacao - Aula #4
Paradigmas de Linguagens de Programacao - Aula #4
 
Constructors and destructors in C++
Constructors and destructors in  C++Constructors and destructors in  C++
Constructors and destructors in C++
 
Virtual Functions
Virtual FunctionsVirtual Functions
Virtual Functions
 
Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014
Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014
Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014
 
Smart Pointers in C++
Smart Pointers in C++Smart Pointers in C++
Smart Pointers in C++
 
Objective c intro (1)
Objective c intro (1)Objective c intro (1)
Objective c intro (1)
 
Fun with Lambdas: C++14 Style (part 2)
Fun with Lambdas: C++14 Style (part 2)Fun with Lambdas: C++14 Style (part 2)
Fun with Lambdas: C++14 Style (part 2)
 
Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)
 
C++ Training
C++ TrainingC++ Training
C++ Training
 

En vedette

What's new in C# 6 - NetPonto Porto 20160116
What's new in C# 6  - NetPonto Porto 20160116What's new in C# 6  - NetPonto Porto 20160116
What's new in C# 6 - NetPonto Porto 20160116Paulo Morgado
 
await Xamarin @ PTXug
await Xamarin @ PTXugawait Xamarin @ PTXug
await Xamarin @ PTXugPaulo Morgado
 
Roslyn analyzers: File->New->Project
Roslyn analyzers: File->New->ProjectRoslyn analyzers: File->New->Project
Roslyn analyzers: File->New->ProjectPaulo Morgado
 
MVP Showcase 2015 - C#
MVP Showcase 2015 - C#MVP Showcase 2015 - C#
MVP Showcase 2015 - C#Paulo Morgado
 
As Novidades Do C# 4.0 - NetPonto
As Novidades Do C# 4.0 - NetPontoAs Novidades Do C# 4.0 - NetPonto
As Novidades Do C# 4.0 - NetPontoPaulo Morgado
 
Async-await best practices in 10 minutes
Async-await best practices in 10 minutesAsync-await best practices in 10 minutes
Async-await best practices in 10 minutesPaulo Morgado
 
Tuga it 2016 - What's New In C# 6
Tuga it 2016 - What's New In C# 6Tuga it 2016 - What's New In C# 6
Tuga it 2016 - What's New In C# 6Paulo Morgado
 
Quintiles new healthreport_2011
Quintiles new healthreport_2011Quintiles new healthreport_2011
Quintiles new healthreport_2011Quintiles
 
DFAIT Usability Final 6 Apr08
DFAIT Usability Final 6 Apr08DFAIT Usability Final 6 Apr08
DFAIT Usability Final 6 Apr08Barry Nesbitt
 
state street corp STT PROXY
state street corp STT PROXYstate street corp STT PROXY
state street corp STT PROXYfinance23
 
Challenge Ecomagination Blog 2011 GE
Challenge Ecomagination Blog 2011 GEChallenge Ecomagination Blog 2011 GE
Challenge Ecomagination Blog 2011 GEptharsocastro
 
User Experience in Action
User Experience in ActionUser Experience in Action
User Experience in ActionUser Vision
 
SD Italian Film Festival Newspaper
SD Italian Film Festival NewspaperSD Italian Film Festival Newspaper
SD Italian Film Festival Newspaperronmiriello
 
L2 cs110 jcu-sindonirev04092011
L2 cs110 jcu-sindonirev04092011L2 cs110 jcu-sindonirev04092011
L2 cs110 jcu-sindonirev04092011Giuseppe Sindoni
 

En vedette (20)

What's new in C# 6 - NetPonto Porto 20160116
What's new in C# 6  - NetPonto Porto 20160116What's new in C# 6  - NetPonto Porto 20160116
What's new in C# 6 - NetPonto Porto 20160116
 
await Xamarin @ PTXug
await Xamarin @ PTXugawait Xamarin @ PTXug
await Xamarin @ PTXug
 
Roslyn analyzers: File->New->Project
Roslyn analyzers: File->New->ProjectRoslyn analyzers: File->New->Project
Roslyn analyzers: File->New->Project
 
MVP Showcase 2015 - C#
MVP Showcase 2015 - C#MVP Showcase 2015 - C#
MVP Showcase 2015 - C#
 
As Novidades Do C# 4.0 - NetPonto
As Novidades Do C# 4.0 - NetPontoAs Novidades Do C# 4.0 - NetPonto
As Novidades Do C# 4.0 - NetPonto
 
Async-await best practices in 10 minutes
Async-await best practices in 10 minutesAsync-await best practices in 10 minutes
Async-await best practices in 10 minutes
 
Tuga it 2016 - What's New In C# 6
Tuga it 2016 - What's New In C# 6Tuga it 2016 - What's New In C# 6
Tuga it 2016 - What's New In C# 6
 
Quintiles new healthreport_2011
Quintiles new healthreport_2011Quintiles new healthreport_2011
Quintiles new healthreport_2011
 
Candela 04 (1)
Candela 04 (1)Candela 04 (1)
Candela 04 (1)
 
Bo 24 06-2013-33 (1)
Bo 24 06-2013-33 (1)Bo 24 06-2013-33 (1)
Bo 24 06-2013-33 (1)
 
DFAIT Usability Final 6 Apr08
DFAIT Usability Final 6 Apr08DFAIT Usability Final 6 Apr08
DFAIT Usability Final 6 Apr08
 
state street corp STT PROXY
state street corp STT PROXYstate street corp STT PROXY
state street corp STT PROXY
 
Carel p co
Carel p coCarel p co
Carel p co
 
Challenge Ecomagination Blog 2011 GE
Challenge Ecomagination Blog 2011 GEChallenge Ecomagination Blog 2011 GE
Challenge Ecomagination Blog 2011 GE
 
User Experience in Action
User Experience in ActionUser Experience in Action
User Experience in Action
 
Icaewjobs.com
Icaewjobs.comIcaewjobs.com
Icaewjobs.com
 
SD Italian Film Festival Newspaper
SD Italian Film Festival NewspaperSD Italian Film Festival Newspaper
SD Italian Film Festival Newspaper
 
L2 cs110 jcu-sindonirev04092011
L2 cs110 jcu-sindonirev04092011L2 cs110 jcu-sindonirev04092011
L2 cs110 jcu-sindonirev04092011
 
Integrating Row Covers & Soil Amendments for Organic Cucumber Production; Gar...
Integrating Row Covers & Soil Amendments for Organic Cucumber Production; Gar...Integrating Row Covers & Soil Amendments for Organic Cucumber Production; Gar...
Integrating Row Covers & Soil Amendments for Organic Cucumber Production; Gar...
 
MODA CATALOG
MODA CATALOGMODA CATALOG
MODA CATALOG
 

Similaire à Whats New In C# 4 0 - NetPonto

devLink - What's New in C# 4?
devLink - What's New in C# 4?devLink - What's New in C# 4?
devLink - What's New in C# 4?Kevin Pilch
 
Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#Juan Pablo
 
Introduction to c sharp 4.0 and dynamic
Introduction to c sharp 4.0 and dynamicIntroduction to c sharp 4.0 and dynamic
Introduction to c sharp 4.0 and dynamicGieno Miao
 
PDC Video on C# 4.0 Futures
PDC Video on C# 4.0 FuturesPDC Video on C# 4.0 Futures
PDC Video on C# 4.0 Futuresnithinmohantk
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side JavascriptJulie Iskander
 
Introduction to c_plus_plus
Introduction to c_plus_plusIntroduction to c_plus_plus
Introduction to c_plus_plusSayed Ahmed
 
Introduction to c_plus_plus (6)
Introduction to c_plus_plus (6)Introduction to c_plus_plus (6)
Introduction to c_plus_plus (6)Sayed Ahmed
 
Getting started with C# Programming
Getting started with C# ProgrammingGetting started with C# Programming
Getting started with C# ProgrammingBhushan Mulmule
 
Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05
Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05
Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05CHOOSE
 
How do you create a programming language for the JVM?
How do you create a programming language for the JVM?How do you create a programming language for the JVM?
How do you create a programming language for the JVM?Federico Tomassetti
 
New microsoft office word document (2)
New microsoft office word document (2)New microsoft office word document (2)
New microsoft office word document (2)rashmita_mishra
 
C questions
C questionsC questions
C questionsparm112
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentalsHCMUTE
 
Is your C# optimized
Is your C# optimizedIs your C# optimized
Is your C# optimizedWoody Pewitt
 
Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Abou Bakr Ashraf
 
12 computer science_notes_ch01_overview_of_cpp
12 computer science_notes_ch01_overview_of_cpp12 computer science_notes_ch01_overview_of_cpp
12 computer science_notes_ch01_overview_of_cppsharvivek
 

Similaire à Whats New In C# 4 0 - NetPonto (20)

devLink - What's New in C# 4?
devLink - What's New in C# 4?devLink - What's New in C# 4?
devLink - What's New in C# 4?
 
Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#
 
Introduction to c sharp 4.0 and dynamic
Introduction to c sharp 4.0 and dynamicIntroduction to c sharp 4.0 and dynamic
Introduction to c sharp 4.0 and dynamic
 
PDC Video on C# 4.0 Futures
PDC Video on C# 4.0 FuturesPDC Video on C# 4.0 Futures
PDC Video on C# 4.0 Futures
 
2.dynamic
2.dynamic2.dynamic
2.dynamic
 
OOC MODULE1.pptx
OOC MODULE1.pptxOOC MODULE1.pptx
OOC MODULE1.pptx
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
Introduction to c_plus_plus
Introduction to c_plus_plusIntroduction to c_plus_plus
Introduction to c_plus_plus
 
Introduction to c_plus_plus (6)
Introduction to c_plus_plus (6)Introduction to c_plus_plus (6)
Introduction to c_plus_plus (6)
 
Getting started with C# Programming
Getting started with C# ProgrammingGetting started with C# Programming
Getting started with C# Programming
 
Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05
Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05
Ralf Laemmel - Not quite a sales pitch for C# 3.0 and .NET's LINQ - 2008-03-05
 
How do you create a programming language for the JVM?
How do you create a programming language for the JVM?How do you create a programming language for the JVM?
How do you create a programming language for the JVM?
 
PostThis
PostThisPostThis
PostThis
 
unit 1 (1).pptx
unit 1 (1).pptxunit 1 (1).pptx
unit 1 (1).pptx
 
New microsoft office word document (2)
New microsoft office word document (2)New microsoft office word document (2)
New microsoft office word document (2)
 
C questions
C questionsC questions
C questions
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
 
Is your C# optimized
Is your C# optimizedIs your C# optimized
Is your C# optimized
 
Visula C# Programming Lecture 6
Visula C# Programming Lecture 6Visula C# Programming Lecture 6
Visula C# Programming Lecture 6
 
12 computer science_notes_ch01_overview_of_cpp
12 computer science_notes_ch01_overview_of_cpp12 computer science_notes_ch01_overview_of_cpp
12 computer science_notes_ch01_overview_of_cpp
 

Plus de Paulo Morgado

NetPonto - The Future Of C# - NetConf Edition
NetPonto - The Future Of C# - NetConf EditionNetPonto - The Future Of C# - NetConf Edition
NetPonto - The Future Of C# - NetConf EditionPaulo Morgado
 
Tuga IT 2018 Summer Edition - The Future of C#
Tuga IT 2018 Summer Edition - The Future of C#Tuga IT 2018 Summer Edition - The Future of C#
Tuga IT 2018 Summer Edition - The Future of C#Paulo Morgado
 
Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7Paulo Morgado
 
C# 6.0 - April 2014 preview
C# 6.0 - April 2014 previewC# 6.0 - April 2014 preview
C# 6.0 - April 2014 previewPaulo Morgado
 
What’s New In C# 5.0 - iseltech'13
What’s New In C# 5.0 - iseltech'13What’s New In C# 5.0 - iseltech'13
What’s New In C# 5.0 - iseltech'13Paulo Morgado
 
What's New In C# 5.0 - Programar 2013
What's New In C# 5.0 - Programar 2013What's New In C# 5.0 - Programar 2013
What's New In C# 5.0 - Programar 2013Paulo Morgado
 
What's new in c# 5.0 net ponto
What's new in c# 5.0   net pontoWhat's new in c# 5.0   net ponto
What's new in c# 5.0 net pontoPaulo Morgado
 

Plus de Paulo Morgado (8)

NetPonto - The Future Of C# - NetConf Edition
NetPonto - The Future Of C# - NetConf EditionNetPonto - The Future Of C# - NetConf Edition
NetPonto - The Future Of C# - NetConf Edition
 
Tuga IT 2018 Summer Edition - The Future of C#
Tuga IT 2018 Summer Edition - The Future of C#Tuga IT 2018 Summer Edition - The Future of C#
Tuga IT 2018 Summer Edition - The Future of C#
 
Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7Tuga IT 2017 - What's new in C# 7
Tuga IT 2017 - What's new in C# 7
 
What's New In C# 7
What's New In C# 7What's New In C# 7
What's New In C# 7
 
C# 6.0 - April 2014 preview
C# 6.0 - April 2014 previewC# 6.0 - April 2014 preview
C# 6.0 - April 2014 preview
 
What’s New In C# 5.0 - iseltech'13
What’s New In C# 5.0 - iseltech'13What’s New In C# 5.0 - iseltech'13
What’s New In C# 5.0 - iseltech'13
 
What's New In C# 5.0 - Programar 2013
What's New In C# 5.0 - Programar 2013What's New In C# 5.0 - Programar 2013
What's New In C# 5.0 - Programar 2013
 
What's new in c# 5.0 net ponto
What's new in c# 5.0   net pontoWhat's new in c# 5.0   net ponto
What's new in c# 5.0 net ponto
 

Dernier

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
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
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
 
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
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
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
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 

Dernier (20)

DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
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
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
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
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
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
 
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
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
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
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 

Whats New In C# 4 0 - NetPonto

  • 1. What's New In C# 4.0
  • 3. The Evolution Of C# Covariance And Contravariance Named And Optional Arguments Dynamic Programming COM Interop Improvements Agenda
  • 8.
  • 13. Colection InitializersC# C# VB Co-Evolution
  • 15. The Evolution Of C# http://paulomorgado.net/en/blog/archive/2010/04/12/the-evolution-of-c.aspx Resources
  • 17. In multilinear algebra and tensor analysis, covariance and contravariance describe how the quantitative description of certain geometrical or physical entities changes when passing from one coordinate system to another. Wikipedia Covariance And Contravarance
  • 18. Type Tis greater than (>) type Sif Sis a subtype of (derives from) T Covariance And Contravarance T≥S typeof(T).IsAssignableFrom(typeof(S))
  • 19. Give 2 types Base and Derived, such that: There is a reference (or identity) conversion between Base and Derived Base ≥ Derived A generic type definition Generic<T> is: Covariant in T If Genérico<Base> ≥ Genérico<Derived> Contravariant in T If Genérico<Base> ≤ Genérico<Derived> Invariant in T If neither of the above apply Covariance And Contravarance
  • 20. Contravariante em T Covariante em T typeof(Base).IsAssignableFrom(typeof(Derived)) typeof(Base).IsAssignableFrom(typeof(Derived)) typeof(G<Derived>).IsAssignableFrom(typeof(G<Base>)) typeof(G<Base>).IsAssignableFrom(typeof(G<Derived>)) Covariance And Contravarance
  • 21. Covariance And Contravarance C# (.NET) arrays are covariant string[] strings = GetStringArray(); Process(strings); … but not safely covariant void Process(object[] objects) { … } void Process(object[] objects) { objects[0] = "Hello"; // Ok objects[1] = newButton(); // Exception! }
  • 22. Covariance And Contravarance Until now, C# (.NET) generics have been invariant List<string> strings = GetStringList(); Process(strings); C# 4.0 supports safe covariance and contravariance void Process(IEnumerable<object> objects) { // IEnumerable<T> is read-only and // therefore safely covariant } void Process(IEnumerable<object> objects) { … }
  • 23. Safe Covariance out= covariant Output positions only publicinterfaceIEnumerable<T> { IEnumerator<T> GetEnumerator(); } publicinterfaceIEnumerable<out T> { IEnumerator<T> GetEnumerator(); } Can be treated as less derived publicinterfaceIEnumerator<T> { T Current { get; } boolMoveNext(); } publicinterfaceIEnumerator<out T> { T Current { get; } boolMoveNext(); } IEnumerable<string> strings = GetStrings(); IEnumerable<object> objects = strings;
  • 24. Safe Contravariance in= contravariantInput positions only Can be treated as more derived publicinterfaceIComparer<T> { int Compare(T x, T y); } publicinterfaceIComparer<in T> { int Compare(T x, T y); } IComparer<object> objComp = GetComparer(); IComparer<string> strComp = objComp;
  • 25. Supported for generic interface and delegate types only. Verified/enforced staticaliy in the definition. Value types are always invariant IEnumerable<int> is not IEnumerable<object> Similar to existing rules for arrays ref and out parameters need invariant types Variance In C# 4.o
  • 27. Covariance And Contravariance In Generics http://paulomorgado.net/en/blog/archive/2010/04/13/c-4-0-covariance-and-contravariance-in-generics.aspx Covariance And Contravariance In Generics Made Easy http://paulomorgado.net/en/blog/archive/2010/04/15/c-4-0-covariance-and-contravariance-in-generics-made-easy.aspx Covarince and Contravariance in Generics http://msdn.microsoft.com/library/dd799517(VS.100).aspx Exact rules for variance validity http://blogs.msdn.com/ericlippert/archive/2009/12/03/exact-rules-for-variância-validity.aspx Events get a little overhaul in C# 4, Afterward: Effective Events http://blogs.msdn.com/cburrows/archive/2010/03/30/events-get-a-little-overhaul-in-c-4-afterward-effective-events.aspx Resources
  • 28. Named And Optional Arguments
  • 29. Named And Optional Arguments Greeting("Mr.", "Morgado", 42); Parameters Arguments public void Greeting(string title, string name, intage) They always have names They are never optional
  • 30. Named Arguments int i = 0; Method(i, third: i++, second: ++i); int i = 0; int CS$0$0000 = i++; int CS$0$0001 = ++i; Method(i, CS$0$0001, CS$0$0000); public void Method(intfirst, intsecond, intthird)
  • 31. Optional Arguments int i = 0; Method(i, third: ++i); int i = 0; int CS$0$0000 = ++i; Method(i, 2, CS$0$0000); public void Method(intfirst, intsecond = 5, intthird = 6) public void Method(intfirst, intsecond = 2, intthird = 3) public void Method(intfirst, intsecond) They look like overloads. But they aren’t! public void Method(intfirst)
  • 32. Argument Classes Optional Arguments - Alternative XmlReaderSettings settings = newXmlReaderSettings(); settings.ValidationType = ValidationType.Auto; XmlReader.Create("file.xml", settings); XmlReader.Create( "file.xml", new { ValidationType = ValidationType.Auto }); XmlReader.Create( "file.xml", newXmlReaderSettings { ValidationType = ValidationType.Auto }); Not yet!
  • 33. C# 4.0: Named And Optional Arguments http://paulomorgado.net/en/blog/archive/2010/04/16/c-4-0-named-and-optional-arguments.aspx C# 4.0: Alternative To Optional Arguments http://paulomorgado.net/en/blog/archive/2010/04/18/c-4-0-alternative-to-optional-arguments.aspx Named and Optional Arguments (C# Programming Guide) http://msdn.microsoft.com/library/dd264739(VS.100).aspx Resources
  • 35. Dynamic Language Runtime IronPython IronRuby C# VB.NET Others… Dynamic Language Runtime Expression Trees Dynamic Dispatch Call Site Caching PythonBinder RubyBinder COMBinder JavaScriptBinder ObjectBinder
  • 36. Objectos Tipados Dinâmicamente Calculatorcalculator = GetCalculator(); int sum = calc.Add(10, 20); object calculator = GetCalculator(); Type calculatorType = calculator.GetType(); object res = calculatorType.InvokeMember("Add", BindingFlags.InvokeMethod, null, calculator, newobject[] { 10, 20 }); int sum = Convert.ToInt32(res); ScriptObject calculator = GetCalculator(); object res = calculator.Invoke("Add", 10, 20); int sum = Convert.ToInt32(res); Statically typed to be dynamic dynamic calc = GetCalculator(); int sum = calc.Add(10, 20); Dynamic method invocation Dynamic conversion
  • 37.
  • 38. At run-time, actual type(s) substituted for dynamic
  • 39.
  • 40. IDynamicMetaObjectProvider Represents a dynamic object that can have operations determined at run-time. DynamicObject : IDynamicMetaObjectProvider Enables you to define which operations can be performed on dynamic objects and how to perform those operations. ExpandoObject : IDynamicMetaObjectProvider Enables you to add and delete members of its instances at run time and also to set and get values of these members. Building Dynamic Objects
  • 41. Dynamic Programming http://paulomorgado.net/en/blog/archive/2010/04/18/c-4-0-dynamic-programming.aspx C# Proposal: Compile Time Static Checking Of Dynamic Objects http://paulomorgado.net/en/blog/archive/2010/03/19/c-proposal-compile-time-static-checking-of-dynamic-objects.aspx Using Type dynamic (C# Programming Guide) http://msdn.microsoft.com/library/dd264736(VS.100).aspx Dynamic Language Runtime Overview http://msdn.microsoft.com/library/dd233052(v=VS.100).aspx Resources
  • 43. Named and optional arguments Ommiting ref Dynamic Import Automatic mapping object -> dynamic Indexed properties Type Equivalence And Type Embedding (“NO PIA”) COM Interop Improvements
  • 44. Ommiting ref objectfileName = "Test.docx"; object missing = Missing.Value; document.SaveAs(reffileName, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); document.SaveAs("Test.docx", Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value); document.SaveAs("Test.docx");
  • 45. Dynamic Import ((Excel.Range)(excel.Cells[1, 1])).Value2 = "Hello World!"; excel.Cells[1, 1] = "Hello World!"; Excel.Range range = (Excel.Range)(excel.Cells[1, 1]); Excel.Rangerange = excel.Cells[1, 1];
  • 46. Type Equivalence And Type Embedding (NO PIA)
  • 47. COM Interop Improvements http://paulomorgado.net/en/blog/archive/2010/04/19/c-4-0-com-interop-improvements.aspx Type Equivalence and Embedded InteropTypes http://msdn.microsoft.com/library/dd997297.aspx Resources
  • 48. Demos
  • 49.
  • 51. The Evolution Of C# Covariance And Contravariance Named And Optional Arguments Dynamic Programming COM Interop Improvements Conclusion
  • 52. Visual C# Developer Center http://csharp.net/ Visual C# 2010 Samples http://code.msdn.microsoft.com/cs2010samples C# Language Specification 4.0 http://www.microsoft.com/downloads/details.aspx?familyid=DFBF523C-F98C-4804-AFBD-459E846B268E&displaylang=en Resources
  • 53. .NET Reflector http://www.red-gate.com/products/reflector/ LINQPad http://linqpad.net/ Paulo Morgado http://PauloMorgado.NET/ Resources

Notes de l'éditeur

  1. The first release of C# (C# 1.0) was all about building a new language for managed code that appealed, mostly, to C++ and Java programmers.The second release (C# 2.0) was mostly about adding what wasn’t time to built into the 1.0 release. The main feature for this release was Generics.The third release (C# 3.0) was all about reducing the impedance mismatch between general purpose programming languages and databases. To achieve this goal, several functional programming features were added to the language and LINQ was born.
  2. Going forward, new trends are showing up in the industry and modern programming languages need to be more:DeclarativeWith imperative languages, although having the eye on the what, programs need to focus on the how. This leads to over specification of the solution to the problem in hand, making next to impossible to the execution engine to be smart about the execution of the program and optimize it to run it more efficiently (given the hardware available, for example).Declarative languages, on the other hand, focus only on the what and leave the how to the execution engine. LINQ made C# more declarative by using higher level constructs like orderby and group by that give the execution engine a much better chance of optimizing the execution (by parallelizing it, for example).ConcurrentConcurrency is hard and needs to be thought about and it’s very hard to shoehorn it into a programming language. Parallel.For (from the parallel extensions) looks like a parallel for because enough expressiveness has been built into C# 3.0 to allow this without having to commit to specific language syntax.DynamicThere was been lots of debate on which ones are the better programming languages: static or dynamic. The fact is that both have good qualities and users of both types of languages want to have it all.All these trends require a paradigm switch. C# is, in many ways, already a multi-paradigm language. It’s still very object oriented (class oriented as some might say) but it can be argued that C# 3.0 has become a functional programming language because it has all the cornerstones of what a functional programming language needs. Moving forward, will have even more.
  3. All these trends require a paradigm switch. C# is, in many ways, already a multi-paradigm language. It’s still very object oriented (class oriented as some might say) but it can be argued that C# 3.0 has become a functional programming language because it has all the cornerstones of what a functional programming language needs. Moving forward, will have even more.Besides the influence of these trends, there was a decision of co-evolution of the C# and Visual Basic programming languages. Since its inception, there was been some effort to position C# and Visual Basic against each other and to try to explain what should be done with each language or what kind of programmers use one or the other. Each language should be chosen based on the past experience and familiarity of the developer/team/project/company and not by particular features.In the past, every time a feature was added to one language, the users of the other wanted that feature too. Going forward, when a feature is added to one language, the other will work hard to add the same feature. This doesn’t mean that XML literals will be added to C# (because almost the same can be achieved with LINQ To XML), but Visual Basic will have auto-implemented properties.Most of these features require or are built on top of features of the .NET Framework and, the focus for C# 4.0 was on dynamic programming. Not just dynamic types but being able to talk with anything that isn’t a .NET class.Also introduced in C# 4.0 is co-variance and contra-variance for generic interfaces and delegates.
  4. C# 4.0 (and .NET 4.0) introduced covariance and contravariance to generic interfaces and delegates. But what is this variance thing?According to Wikipedia, in multilinear algebra and tensor analysis, covariance and contravariance describe how the quantitative description of certain geometrical or physical entities changes when passing from one coordinate system to another.(*)
  5. But what does this have to do with C# or .NET?In type theory, a the type T is greater (&gt;) than type S if S is a subtype (derives from) T, which means that there is a quantitative description for types in a type hierarchy.So, how does covariance and contravariance apply to C# (and .NET) generic types?
  6. In C# (and .NET), variance is a relation between a generic type definition and a particular generic type parameter.Given two types Base and Derived, such that:There is a reference (or identity) conversion between Base and DerivedBase ≥ DerivedA generic type definition Generic&lt;T&gt; is:covariant in T if the ordering of the constructed types follows the ordering of the generic type parameters: Generic&lt;Base&gt; ≥ Generic&lt;Derived&gt;. contravariant in T if the ordering of the constructed types is reversed from the ordering of the generic type parameters: Generic&lt;Base&gt; ≤ Generic&lt;Derived&gt;. invariant in T if neither of the above apply.
  7. If this definition is applied to arrays, we can see that arrays have always been covariant in relation to the type of the elements because this is valid code:object[] objectArray = new string[] { &quot;string 1&quot;, &quot;string 2&quot; };objectArray[0] = &quot;string 3&quot;;objectArray[1] = new object();However, when we try to run this code, the second assignment will throw an ArrayTypeMismatchException. Although the compiler was fooled into thinking this was valid code because an object is being assigned to an element of an array ofobject, at run time, there is always a type check to guarantee that the runtime type of the definition of the elements of the array is greater or equal to the instance being assigned to the element. In the above example, because the runtime type of the array is array of string, the first assignment of array elements is valid because string ≥ string and the second is invalid because string ≤ object.This leads to the conclusion that, although arrays have always been covariant in relation to the type of the elements, they are not safely covariant – code that compiles is not guaranteed to run without errors.
  8. In C#, variance is enforced in the declaration of the type and not determined by the usage of each the generic type parameter.Covariance in relation to a particular generic type parameter is enforced, is using the out generic modifier.Notice the convenient use the pre-existing out keyword. Besides the benefit of not having to remember a new hypothetic covariant keyword, out is easier to remember because it defines that the generic type parameter can only appear in output positions — read-only properties and method return values.
  9. In a similar way, the way contravariance is enforced in relation a particular generic type parameter, is using the in generic modifier.Once again, the use of the pre-existing in keyword makes it easier to remember that the generic type parameter can only be used in input positions — write-only properties and method non ref and non out parameters.
  10. A generic type parameter that is not marked covariant (out) or contravariant (in) is invariant.Because covariance and contravariance applies to the relation between a generic type definition and a particular generic type parameter, a generic type definition can be both covariant, contravariant and invariant depending on the generic type parameter.In the above delegate definition, Func&lt;T, TResult&gt; is contravariant in T and convariant in TResult.All the types in the .NET Framework where variance could be applied to its generic type parameters have been modified to take advantage of this new feature.In summary, the rules for variance in C# (and .NET) are:Variance in relation to generic type parameters is restricted to generic interface and generic delegate type definitions.A generic interface or generic delegate type definition can be covariant, contravariant or invariant in relation to different generic type parameters.Variance applies only to reference types: a IEnumerable&lt;int&gt; is not an IEnumerable&lt;object&gt;.Variance does not apply to delegate combination. That is, given two delegates of types Action&lt;Derived&gt; and Action&lt;Base&gt;, you cannot combine the second delegate with the first although the result would be type safe. Variance allows the second delegate to be assigned to a variable of type Action&lt;Derived&gt;, but delegates can combine only if their types match exactly.If you want to learn more about variance in C# (and .NET), you can always read:Covariance and Contravariance in Generics — MSDN LibraryExact rules for variance validity — Eric LippertEvents get a little overhaul in C# 4, Afterward: Effective Events — Chris BurrowsNote: Because variance is a feature of .NET 4.0 and not only of C# 4.0, all this also applies to Visual Basic 10.
  11. As part of the co-evolution effort of C# and Visual Basic, C# 4.0 introduces Named and Optional Arguments.First of all, let’s clarify what are arguments and parameters:Method definition parameters are the input variables of the method.Method call arguments are the values provided to the method parameters.In fact, the C# Language Specification states the following on §7.5:The argument list (§7.5.1) of a function member invocation provides actual values or variable references for the parameters of the function member.Given the above definitions, we can state that:Parameters have always been named and still are.Parameters have never been optional and still aren’t.
  12. Until now, the way the C# compiler matched method call definition arguments with method parameters was by position. The first argument provides the value for the first parameter, the second argument provides the value for the second parameter, and so on and so on, regardless of the name of the parameters. If a parameter was missing a corresponding argument to provide its value, the compiler would emit a compilation error.For this call:Greeting(&quot;Mr.&quot;, &quot;Morgado&quot;, 42); this method:public void Greeting(string title, string name, intage)will receive as parameters:title: “Mr.”name: “Morgado”age: 42What this new feature allows is to use the names of the parameters to identify the corresponding arguments in the form: name:valueNot all arguments in the argument list must be named. However, all named arguments must be at the end of the argument list. The matching between arguments (and the evaluation of its value) and parameters will be done first by name for the named arguments and than by position for the unnamed arguments.This means that, for this method definition:public void Method(intfirst, intsecond, intthird) this call declaration:inti = 0; Method(i, third: i++, second: ++i); will have this code generated by the compiler:inti = 0; intCS$0$0000 = i++; intCS$0$0001 = ++i; Method(i, CS$0$0001, CS$0$0000); which will give the method the following parameter values:first: 2 second: 2 third: 0 Notice the variable names. Although invalid being invalid C# identifiers, they are valid .NET identifiers and thus avoiding collision between user written and compiler generated code.Besides allowing to re-order of the argument list, this feature is very useful for auto-documenting the code, for example, when the argument list is very long or not clear, from the call site, what the arguments are.
  13. Parameters can now have default values:public void Method(intfirst, intsecond = 2, intthird = 3) Parameters with default values must be the last in the parameter list and its value is used as the value of the parameter if the corresponding argument is missing from the method call declaration.For this call declaration:inti = 0; Method(i, third: ++i); will have this code generated by the compiler:inti = 0; intCS$0$0000 = ++i; Method(i, 2, CS$0$0000); which will give the method the following parameter values:first: 1 second: 2 third: 1 Because, when method parameters have default values, arguments can be omitted from the call declaration, this might seem like method overloading or a good replacement for it, but it isn’t.Although methods like this:public StreamReaderOpenTextFile(string path,Encoding encoding = null,booldetectEncoding = true,intbufferSize = 1024) allow to have its calls written like this:OpenTextFile(&quot;foo.txt&quot;, Encoding.UTF8); OpenTextFile(&quot;foo.txt&quot;, Encoding.UTF8, bufferSize: 4096); OpenTextFile(bufferSize: 4096, path: &quot;foo.txt&quot;,detectEncoding: false); The complier handles default values like constant fields taking the value and useing it instead of a reference to the value. So, like with constant fields, methods with parameters with default values are exposed publicly (and remember that internal members might be publicly accessible – InternalsVisibleToAttribute). If such methods are publicly accessible and used by another assembly, those values will be hard coded in the calling code and, if the called assembly has its default values changed, they won’t be assumed by already compiled code.At the first glance, I though that using optional arguments for “bad” written code was great, but the ability to write code like that was just pure evil. But than I realized that, since I use private constant fields, it’s OK to use default parameter values on privately accessed methods.
  14. Like I mentioned in my last post, exposing publicly methods with optional arguments is a bad practice (that’s why C# has resisted to having it, until now).You might argument that your method or constructor has to many variants and having ten or more overloads is a maintenance nightmare, and you’re right. But the solution has been there for ages: have an arguments class.The arguments class pattern is used in the .NET Framework is used by several classes, like XmlReader and XmlWriter that use such pattern in their Create methods, since version 2.0:XmlReaderSettingssettings = new XmlReaderSettings(); settings.ValidationType = ValidationType.Auto; XmlReader.Create(&quot;file.xml&quot;, settings); With this pattern, you don’t have to maintain a long list of overloads and any default values for properties of XmlReaderSettings (or XmlWriterSettings for XmlWriter.Create) can be changed or new properties added in future implementations that won’t break existing compiled code.You might now argue that it’s too much code to write, but, with object initializers added in C# 3.0, the same code can be written like this:XmlReader.Create(&quot;file.xml&quot;, new XmlReaderSettings{ ValidationType = ValidationType.Auto }); Looks almost like named and optional arguments, doesn’t it? And, who knows, in a future version of C#, it might even look like this:XmlReader.Create(&quot;file.xml&quot;, new { ValidationType = ValidationType.Auto });
  15. The major feature of C# 4.0 is dynamic programming. Not just dynamic typing, but dynamic in broader sense, which means talking to anything that is not statically typed to be a .NET object.Dynamic Language RuntimeThe Dynamic Language Runtime (DLR) is piece of technology that unifies dynamic programming on the .NET platform, the same way the Common Language Runtime (CLR) has been a common platform for statically typed languages.The CLR always had dynamic capabilities. You could always use reflection, but its main goal was never to be a dynamic programming environment and there were some features missing. The DLR is built on top of the CLR and adds those missing features to the .NET platform.The Dynamic Language Runtime is the core infrastructure that consists of:Expression TreesThe same expression trees used in LINQ, now improved to support statements.Dynamic DispatchDispatches invocations to the appropriate binder.Call Site CachingFor improved efficiency.Dynamic languages and languages with dynamic capabilities are built on top of the DLR. IronPython and IronRuby were already built on top of the DLR, and now, the support for using the DLR is being added to C# and Visual Basic. Other languages built on top of the CLR are expected to also use the DLR in the future.Underneath the DLR there are binders that talk to a variety of different technologies:.NET BinderAllows to talk to .NET objects.JavaScript BinderAllows to talk to JavaScript in SilverLight.IronPython BinderAllows to talk to IronPython.IronRuby BinderAllows to talk to IronRuby.COM BinderAllows to talk to COM.Whit all these binders it is possible to have a single programming experience to talk to all these environments that are not statically typed .NET objects.
  16. Let’s take this traditional statically typed code:Calculator calculator = GetCalculator(); intsum = calculator.Sum(10, 20); Because the variable that receives the return value of the GetCalulator method is statically typed to be of type Calculator and, because the Calculator type has an Add method that receives two integers and returns an integer, it is possible to call that Sum method and assign its return value to a variable statically typed as integer.Now lets suppose the calculator was not a statically typed .NET class, but, instead, a COM object or some .NET code we don’t know he type of. All of the sudden it gets very painful to call the Add method:object calculator = GetCalculator(); Type calculatorType = calculator.GetType(); object res = calculatorType.InvokeMember(&quot;Add&quot;, BindingFlags.InvokeMethod, null, calculator, new object[] { 10, 20 }); intsum = Convert.ToInt32(res); And what if the calculator was a JavaScript object?ScriptObjectcalculator = GetCalculator(); object res = calculator.Invoke(&quot;Add&quot;, 10, 20); intsum = Convert.ToInt32(res); For each dynamic domain we have a different programming experience and that makes it very hard to unify the code.With C# 4.0 it becomes possible to write code this way:dynamic calculator = GetCalculator(); intsum = calculator.Add(10, 20); You simply declare a variable who’s static type is dynamic. dynamic is a pseudo-keyword (like var) that indicates to the compiler that operations on the calculator object will be done dynamically.The way you should look at dynamic is that it’s just like object (System.Object) with dynamic semantics associated. Anything can be assigned to a dynamic.
  17. At run-time, all object will have a type. In the above example x is of type System.Int32.When one or more operands in an operation are typed dynamic, member selection is deferred to run-time instead of compile-time. Then the run-time type is substituted in all variables and normal overload resolution is done, just like it would happen at compile-time.
  18. The result of any dynamic operation is always dynamic and, when a dynamic object is assigned to something else, a dynamic conversion will occur.double x = 1.75; double y = Math.Abs(x);Compile-timedouble Abs(double x)dynamic x = 1.75; dynamic y = Math.Abs(x);Run-timedouble Abs(double x)dynamic x = 2; dynamic y = Math.Abs(x);Run-timeint Abs(int x)The above code will always be strongly typed. The difference is that, in the first case the method resolution is done at compile-time, and the others it’s done ate run-time.
  19. The DLR is pre-wired to know .NET objects, COM objects and so forth but any dynamic language can implement their own objects or you can implement your own objects in C# through the implementation of the IDynamicMetaObjectProvider interface. When an object implements IDynamicMetaObjectProvider, it can participate in the resolution of how method calls and property access is done.The .NET Framework already provides two implementations of IDynamicMetaObjectProvider:DynamicObject : IDynamicMetaObjectProviderThe DynamicObject class enables you to define which operations can be performed on dynamic objects and how to perform those operations. For example, you can define what happens when you try to get or set an object property, call a method, or perform standard mathematical operations such as addition and multiplication.ExpandoObject : IDynamicMetaObjectProviderThe ExpandoObject class enables you to add and delete members of its instances at run time and also to set and get values of these members. This class supports dynamic binding, which enables you to use standard syntax like sampleObject.sampleMember, instead of more complex syntax like sampleObject.GetAttribute(&quot;sampleMember&quot;).
  20. Dynamic resolution as well as named and optional arguments greatly improve the experience of interoperating with COM APIs such as Office Automation Primary Interop Assemblies (PIAs). But, in order to alleviate even more COMInterop development, a few COM-specific features were also added to C# 4.0.
  21. Because of a different programming model, many COM APIs contain a lot of reference parameters. These parameters are typically not meant to mutate a passed-in argument, but are simply another way of passing value parameters.Specifically for COM methods, the compiler allows to declare the method call passing the arguments by value and will automatically generate the necessary temporary variables to hold the values in order to pass them by reference and will discard their values after the call returns. From the point of view of the programmer, the arguments are being passed by value.
  22. Dynamic ImportMany COM methods accept and return variant types, which are represented in the PIAs as object. In the vast majority of cases, a programmer calling these methods already knows the static type of a returned object form the context of the call, but has to explicitly perform a cast on the returned values to make use of that knowledge. These casts are so common that they constitute a major nuisance.To make the developer’s life easier, it is now possible to import the COM APIs in such a way that variants are instead represented using the type dynamic which means that COM signatures have now occurrences of dynamic instead of object.This means that members of a returned object can now be easily accessed or assigned into a strongly typed variable without having to cast.Indexed And Default PropertiesA few COM interface features are still not available in C#. On the top of the list are indexed properties and default properties. As mentioned above, these will be possible if the COM interface is accessed dynamically, but will not be recognized by statically typed C# code.
  23. For assemblies indentified with PrimaryInteropAssemblyAttribute, the compiler will create equivalent types (interfaces, structs, enumerations and delegates) and embed them in the generated assembly.To reduce the final size of the generated assembly, only the used types and their used members will be generated and embedded.Although this makes development and deployment of applications using the COM components easier because there’s no need to deploy the PIAs, COM component developers are still required to build the PIAs.