SlideShare ist ein Scribd-Unternehmen logo
1 von 14
Downloaden Sie, um offline zu lesen
1 
New C#4 Features – Part II 
Nico Ludwig (@ersatzteilchen)
2 
TOC 
● New C#4 Features – Part II 
– New generic Types of the BCL in Detail: Lazy<T> and Tuple<T, ...> 
– Generic Variance 
● Sources: 
– Jon Skeet, CSharp in Depth 
– Chamond Liu, Smalltalk, Objects, Design
3 
New generic BCL Types 
<NewGenericBCLTypes> 
TShows the type Lazy<T>, Tuples and structural comparison 
with Tuples and arrays.
4 
Lazy<T> 
● Lazy<T> provides simple support for deferred initialization. 
– Idiomatic usage as (encapsulated) field of a type. 
● Lazy initialization w/ dctors as well as w/ initializer functions is supported. 
● Threadsafe initialization is supported.
5 
Tuples – Part I 
● Tuples are known from functional programming as ad hoc data structure. 
– A Tuple is: Basically a list of values (called components) of possibly different static types. 
– They have been introduced to use F# APIs that make use of Tuples. 
– .Net Tuples are ordinary generic types, but can have any number of components. 
● There are generic overloads for up to seven components. 
● This limit can be overcome by cascading Tuples. 
● Tuples vs. anonymous types: 
– Only Tuples (as static type) can be returned from methods and passed to methods. 
– Only anonymous types have semantic quality, Tuples are rather data containers. 
– Both override Equals() and GetHashCode() in order to express value semantics. 
– Both are immutable in C#. 
● Slightly like Lisp's concept of cons-cells. 
● As the Tuple-types are not sealed you could 
derive your own implementation containing 
extra behavior. - But that's questionable as you 
can't hide possibly unwanted information (like 
the ItemX-properties accessing the 
components). 
● Tuples can't be XML serialized (this esp. 
includes that they don't have a dctor).
6 
Tuples – Part II 
● Pro: 
– Allow creating more composable APIs. 
● As alternative to passing back results with out/ref. 
● Also very handy as return type of anonymous functions (e.g. in TPL code). 
– Support structural comparison. 
● New in .Net 4: arrays also implement IStructuralEquatable and IStructuralComparable explicitly. 
– Allow exploiting F# APIs that deal with Tuples. 
● Contra: 
– As they have fixed property names, they have very limited semantics. 
● Limit their usage to return types and parameter types. 
● Understand and use them as data containers. 
– Can't be used in web service interfaces, as Tuples can not be accordingly serialized. 
● Using of Tuples can be better than anonymous 
types, if you need to return the result of an 
anonymous function from an enclosing _named_ 
function! 
● Tuples are fine to create fluent APIs, as they allow 
to get rid of ref and out parameters.
7 
Consistency of Type Hierarchies: Covariance 
● What does "consistency" mean? 
– The idea is to design type-safe type hierarchies with highly substitutable types. 
– The key to get this consistency is subtype or subclass based conformance. 
– (We'll discuss the Liskov Substitution Principle (LSP) on a high level here.) 
● Example: Let's assume Birds that lay Eggs "consistently" with static typing: 
– If the type Bird lays an Egg, wouldn't a Bird's subtype lay a subtype of Egg? 
– E.g. the type Duck lays a DuckEgg; then the consistency is given like so: 
DuckEgg 
– Why is this consistent? Because in such an expression (no C#!): 
+ Lay : Egg 
Egg anEgg = aBird.Lay() 
Bird 
the reference aBird could be legally substituted by a Bird or by a Duck instance. 
– We say the return type is covariant to the type, in which Lay() is defined. 
– A subtype's override may return a more specialized type. => "They deliver more." 
Duck 
+ Lay : DuckEgg 
Egg 
● The term sub typing is used here a little sloppy. 
Virtually the terms sub typing and sub classing 
have different meanings when discussing 
substitutability, but the difference is not relevant 
here. 
● The LSP was introduced by Prof. (MIT) Barbara 
Liskov in 1987. 
● Covariance is esp. handy on abstract factories. 
● Exception specifications in C++ and Java are also 
covariant (as they are similar to return types). 
● Covariance/contravariance are terms taken from 
the mathematical "category theory" that deals with 
the substitution principle.
8 
Consistency of Type Hierarchies: Contravariance 
● Let's assume Pianos that Pianists can play "consistently" with static typing: 
– If a Pianist plays Piano, would she be able to play aGrandPiano? 
– Wouldn't rather a Virtuoso play a GrandPiano? (Be warned; there is a twist!) 
Virtuoso 
– This is inconsistent! Because in such an expression (no C#): 
+ Play(player : Pianist) 
aPiano.Play(aPianist) 
Piano 
– aPiano couldn't be legally substituted by a Piano or by a GrandPiano instance! A GrandPiano can only be played by a Virtuoso, 
Pianists are too general! 
– GrandPianos must be playable by more general types, then the play is consistent: 
– We say the parameter type is contravariant to the type, in which Play() is defined. 
– A subtype's override may accept a more generalized type. => "They require less." 
GrandPiano 
+ Play(player : Virtuoso) 
Pianist 
Pianist 
Piano 
+ Play(player : Pianist) 
GrandPiano 
+ Play(player : Person) 
Person 
● The described conformance (covariant return 
types/contravariant parameter types) is the 
theoretical ideal (supported by the languages 
Emerald and POOL-1). Some oop languages (e.g. 
Eiffel) decided to apply another type of 
consistency, esp. also covariant parameter types, 
because it better describes the reality than the 
theoretical ideal. 
● In statically typed languages the desired 
consistency must often be achieved by application 
of design patterns like "double dispatching" and 
"visitor". Other languages provide so-called 
"multiple dispatch" (e.g. CLOS) or get the desired 
effect by using dynamic typing.
9 
Problems with covariant Arrays in C# 
<IntrinsicCSharpCovarianceWArrays> 
Shows the problem with covariance of arrays in C#.
10 
Put the Consistency Theory into Practice with C#4 
● Variance expresses the consistency of type-safe type substitution. 
● C# does already provide covariance on arrays. 
– Yes, it's not type-safe, but can we do anything more to reach better consistency? 
● Yes, via generic variance available in C#4! 
– (But C#'s consistency is still based on invariant return and parameter types!) 
● So, you can enable variances on generic delegate and interface types. 
– This feature was present since .Net 2, it was enabled for C# in C#4. 
– The idea is to define the variance of return and parameter types individually. 
– Different variances can be mixed in a specific delegate or interface. 
– With variance, the compiler will treat in and out - types differently, so that variant generic types act as if they were related. 
● Covariance on arrays works only w/ reference 
conversions: inheritance and interface (of 
implicitly or explicitly implemented interfaces) 
conversions. (No boxing, value type or user 
conversions are allowed!) 
● Try to limit the usage of array parameters to 
param-arrays, as they are much safer. 
● In C# no covariant return types are available (in 
opposite to Java and C++). 
● In C# methods with out and ref parameters are 
also not variant on that parameters. 
● Variance can only be declared on generic 
interfaces and delegates, not on classes or 
structs. => It does not work without explicitly 
refactoring type hierarchies.
11 
Generic Interface Variance in Action 
<CSharpCovariance> 
This example shows generic interface variance in C#. 
● No example dealing with generic variance on 
delegates will be presented here. But you can 
find some examples in the source code 
accompanying this presentation.
12 
Summary: generic Variance 
● What is generic interface/delegate variance? 
– It allows "reasonable" implicit conversions between unrelated types to occur. 
● So the main features variance enables are co- and contravariant conversions. 
– It reduces the amount of compile time errors. 
● But only reference conversions of return and parameter types can be used! 
– (As with array covariance: no boxing, value type or user conversions are allowed!) 
● Possibly you'll never code own variant types, but you'll exploit existing ones. 
– Some .Net types have been made variant: IEnumerable<out T>/IEnumerator<out T>, IComparable<in T>, Action<in T, ...>, 
Func<out T, in R, ..>, Converter<in T, out R>. 
● Pitfalls with variant types: 
– New implicit conversions are in avail: type checks and overloads behave differently. 
– Generic variance on delegates does not work with multicasting. 
● Example application: return types of factory 
interfaces. 
● Reference conversions: inheritance and interface 
(of implicitly or explicitly implemented interfaces) 
conversions. 
● .Net collection types must stay invariant as they 
use the same parametrized type for return and 
parameter values. 
● The problem with multicasting might be fixed with 
a future .Net version. 
● Before generic variance was enabled with C#4 
there was a way to simulate covariance 
(see: 
http://blogs.msdn.com/b/kcwalina/archive/2008/0 
4/02/simulatedcovariance.aspx 
).
13 
Variance "Mechanics" 
● Expressing generic variance on interfaces: 
interface IFactory<out T> 
{ // Covariant on T. 
T Produce(); 
} 
● Expressing generic variance on delegates: 
// Covariant on T. 
delegate T Func<out T>(); 
● Restrictions on expressing generic variance: 
– Only interface and delegate variance is supported. 
interface IAcceptor<in T> 
{ // Contravariant on T. 
void Accept(T t); 
} 
// Contravariant on T. 
delegate void Action<in T>(T t); 
– Due to guaranteed static type-safety, return types can only be covariant and parameter types can only be contravariant! 
● You have to declare the variance on the type parameters explicitly! 
● You can not express your own consistency, esp. no consistency can be expressed on exceptions. 
– If T is a return type and a parameter type that type must be invariant. 
– out method parameters are always invariant, as they are CLR ref parameters! 
● The C# compiler could, at least in most cases, infer the 
right variances; but you have to declare variances 
explicitly, because it might lead to breaking code. 
● Since exceptions are not part of signatures in C#, no 
consistency can be declared on them. 
● Because out method parameters can also be used to 
pass data to a method they can not be safely covariant 
as return types. The CLR does not make a difference 
between out and ref parameters. 
● In Java, variances are expressed on the caller side of 
the (generic) type, i.e. nothing must be declared on the 
type itself to act variant. - C# uses statically checked 
definition-site variance (so does Scala). 
● In dynamic languages the consistency is often present 
intrinsically, because substitutability is not expressed 
by static types, but by common interfaces (read: couple 
of methods). - Subtyping instead of subclassing is used 
here: more on this in following lectures. 
● The IL syntax uses the symbols +/-T to denote the type 
of variance (the Scala syntax is similar).
14 
Thank you!

Weitere ähnliche Inhalte

Was ist angesagt?

Coding style of Linux Kernel
Coding style of Linux KernelCoding style of Linux Kernel
Coding style of Linux Kernel
Peter Chang
 
Looping and switch cases
Looping and switch casesLooping and switch cases
Looping and switch cases
MeoRamos
 

Was ist angesagt? (20)

Clean code
Clean codeClean code
Clean code
 
F# for Scala developers
F# for Scala developersF# for Scala developers
F# for Scala developers
 
Objective-C to Swift - Swift Cloud Workshop 3
Objective-C to Swift - Swift Cloud Workshop 3Objective-C to Swift - Swift Cloud Workshop 3
Objective-C to Swift - Swift Cloud Workshop 3
 
Learn C# Programming - Variables & Constants
Learn C# Programming - Variables & ConstantsLearn C# Programming - Variables & Constants
Learn C# Programming - Variables & Constants
 
JavaScript: Core Part
JavaScript: Core PartJavaScript: Core Part
JavaScript: Core Part
 
Whats new in Java 7
Whats new in Java 7Whats new in Java 7
Whats new in Java 7
 
Why functional programming in C# & F#
Why functional programming in C# & F#Why functional programming in C# & F#
Why functional programming in C# & F#
 
Switch statement
Switch statementSwitch statement
Switch statement
 
Coding style of Linux Kernel
Coding style of Linux KernelCoding style of Linux Kernel
Coding style of Linux Kernel
 
Ionuț G. Stan - Let’s write a type checker at I T.A.K.E. Unconference 2015
Ionuț G. Stan - Let’s write a type checker at I T.A.K.E. Unconference 2015Ionuț G. Stan - Let’s write a type checker at I T.A.K.E. Unconference 2015
Ionuț G. Stan - Let’s write a type checker at I T.A.K.E. Unconference 2015
 
(3) c sharp introduction_basics_part_ii
(3) c sharp introduction_basics_part_ii(3) c sharp introduction_basics_part_ii
(3) c sharp introduction_basics_part_ii
 
Looping and switch cases
Looping and switch casesLooping and switch cases
Looping and switch cases
 
Introduction to JVM languages and Fantom (very brief)
Introduction to JVM languages and Fantom (very brief)Introduction to JVM languages and Fantom (very brief)
Introduction to JVM languages and Fantom (very brief)
 
RegexCat
RegexCatRegexCat
RegexCat
 
Master in javascript
Master in javascriptMaster in javascript
Master in javascript
 
C++ c#
C++ c#C++ c#
C++ c#
 
Theperlreview
TheperlreviewTheperlreview
Theperlreview
 
Recapping C# 6.0 and A First Look Into C# 7.0
Recapping C# 6.0 and A First Look Into C# 7.0Recapping C# 6.0 and A First Look Into C# 7.0
Recapping C# 6.0 and A First Look Into C# 7.0
 
Integers pointers | By Vikram Snehi
Integers pointers | By Vikram SnehiIntegers pointers | By Vikram Snehi
Integers pointers | By Vikram Snehi
 
Grooming with Groovy
Grooming with GroovyGrooming with Groovy
Grooming with Groovy
 

Andere mochten auch

SVR17: Data-Intensive Computing on Windows HPC Server with the ...
SVR17: Data-Intensive Computing on Windows HPC Server with the ...SVR17: Data-Intensive Computing on Windows HPC Server with the ...
SVR17: Data-Intensive Computing on Windows HPC Server with the ...
butest
 
Introduction to Reactive Extensions
Introduction to Reactive ExtensionsIntroduction to Reactive Extensions
Introduction to Reactive Extensions
Peter Goodman
 
Reactive Extensions
Reactive ExtensionsReactive Extensions
Reactive Extensions
Kiev ALT.NET
 
Pertemuan 1. introduction to image processing
Pertemuan 1. introduction to image processingPertemuan 1. introduction to image processing
Pertemuan 1. introduction to image processing
Aditya Kurniawan
 
Introduction To Csharp
Introduction To CsharpIntroduction To Csharp
Introduction To Csharp
sarfarazali
 
Getting the MVVM Kicked Out of Your F#'n Monads
Getting the MVVM Kicked Out of Your F#'n MonadsGetting the MVVM Kicked Out of Your F#'n Monads
Getting the MVVM Kicked Out of Your F#'n Monads
Richard Minerich
 
Texas STaR
Texas STaRTexas STaR
Texas STaR
llyarbro
 
F# with Excel at F# in Finance, London Nov 2013
F# with Excel at F# in Finance, London Nov 2013F# with Excel at F# in Finance, London Nov 2013
F# with Excel at F# in Finance, London Nov 2013
Adam Mlocek
 

Andere mochten auch (20)

Test first
Test firstTest first
Test first
 
New c sharp4_features_part_v
New c sharp4_features_part_vNew c sharp4_features_part_v
New c sharp4_features_part_v
 
SVR17: Data-Intensive Computing on Windows HPC Server with the ...
SVR17: Data-Intensive Computing on Windows HPC Server with the ...SVR17: Data-Intensive Computing on Windows HPC Server with the ...
SVR17: Data-Intensive Computing on Windows HPC Server with the ...
 
New c sharp4_features_part_vi
New c sharp4_features_part_viNew c sharp4_features_part_vi
New c sharp4_features_part_vi
 
New c sharp4_features_part_iii
New c sharp4_features_part_iiiNew c sharp4_features_part_iii
New c sharp4_features_part_iii
 
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
 
New c sharp4_features_part_iv
New c sharp4_features_part_ivNew c sharp4_features_part_iv
New c sharp4_features_part_iv
 
Introduction to F#x
Introduction to F#xIntroduction to F#x
Introduction to F#x
 
Introduction to Reactive Extensions
Introduction to Reactive ExtensionsIntroduction to Reactive Extensions
Introduction to Reactive Extensions
 
Reactive Extensions
Reactive ExtensionsReactive Extensions
Reactive Extensions
 
Introduction to C# 3.0
Introduction to C# 3.0Introduction to C# 3.0
Introduction to C# 3.0
 
Pertemuan 1. introduction to image processing
Pertemuan 1. introduction to image processingPertemuan 1. introduction to image processing
Pertemuan 1. introduction to image processing
 
New c sharp3_features_(linq)_part_v
New c sharp3_features_(linq)_part_vNew c sharp3_features_(linq)_part_v
New c sharp3_features_(linq)_part_v
 
F:\Universidad Tecnologica Israel
F:\Universidad Tecnologica IsraelF:\Universidad Tecnologica Israel
F:\Universidad Tecnologica Israel
 
Introduction To Csharp
Introduction To CsharpIntroduction To Csharp
Introduction To Csharp
 
The Power of F#
The Power of F#The Power of F#
The Power of F#
 
Texas
TexasTexas
Texas
 
Getting the MVVM Kicked Out of Your F#'n Monads
Getting the MVVM Kicked Out of Your F#'n MonadsGetting the MVVM Kicked Out of Your F#'n Monads
Getting the MVVM Kicked Out of Your F#'n Monads
 
Texas STaR
Texas STaRTexas STaR
Texas STaR
 
F# with Excel at F# in Finance, London Nov 2013
F# with Excel at F# in Finance, London Nov 2013F# with Excel at F# in Finance, London Nov 2013
F# with Excel at F# in Finance, London Nov 2013
 

Ähnlich wie New c sharp4_features_part_ii

New c sharp3_features_(linq)_part_iv
New c sharp3_features_(linq)_part_ivNew c sharp3_features_(linq)_part_iv
New c sharp3_features_(linq)_part_iv
Nico Ludwig
 
03 expressions.ppt
03 expressions.ppt03 expressions.ppt
03 expressions.ppt
Business man
 

Ähnlich wie New c sharp4_features_part_ii (20)

New c sharp3_features_(linq)_part_ii
New c sharp3_features_(linq)_part_iiNew c sharp3_features_(linq)_part_ii
New c sharp3_features_(linq)_part_ii
 
(6) c sharp introduction_advanced_features_part_i
(6) c sharp introduction_advanced_features_part_i(6) c sharp introduction_advanced_features_part_i
(6) c sharp introduction_advanced_features_part_i
 
Review of c_sharp2_features_part_iii
Review of c_sharp2_features_part_iiiReview of c_sharp2_features_part_iii
Review of c_sharp2_features_part_iii
 
New c sharp3_features_(linq)_part_iv
New c sharp3_features_(linq)_part_ivNew c sharp3_features_(linq)_part_iv
New c sharp3_features_(linq)_part_iv
 
(6) c sharp introduction_advanced_features_part_i
(6) c sharp introduction_advanced_features_part_i(6) c sharp introduction_advanced_features_part_i
(6) c sharp introduction_advanced_features_part_i
 
(4) c sharp introduction_object_orientation_part_i
(4) c sharp introduction_object_orientation_part_i(4) c sharp introduction_object_orientation_part_i
(4) c sharp introduction_object_orientation_part_i
 
(4) cpp automatic arrays_pointers_c-strings
(4) cpp automatic arrays_pointers_c-strings(4) cpp automatic arrays_pointers_c-strings
(4) cpp automatic arrays_pointers_c-strings
 
2.Getting Started with C#.Net-(C#)
2.Getting Started with C#.Net-(C#)2.Getting Started with C#.Net-(C#)
2.Getting Started with C#.Net-(C#)
 
F# Intro for Scala Developers
F# Intro for Scala DevelopersF# Intro for Scala Developers
F# Intro for Scala Developers
 
c# at f#
c# at f#c# at f#
c# at f#
 
C# AND F#
C# AND F#C# AND F#
C# AND F#
 
Functional Programming in C# and F#
Functional Programming in C# and F#Functional Programming in C# and F#
Functional Programming in C# and F#
 
Review of c_sharp2_features_part_i
Review of c_sharp2_features_part_iReview of c_sharp2_features_part_i
Review of c_sharp2_features_part_i
 
(2) cpp imperative programming
(2) cpp imperative programming(2) cpp imperative programming
(2) cpp imperative programming
 
New c sharp4_features_part_i
New c sharp4_features_part_iNew c sharp4_features_part_i
New c sharp4_features_part_i
 
(3) cpp procedural programming
(3) cpp procedural programming(3) cpp procedural programming
(3) cpp procedural programming
 
22 Jop Oct 08
22 Jop Oct 0822 Jop Oct 08
22 Jop Oct 08
 
New c sharp3_features_(linq)_part_iv
New c sharp3_features_(linq)_part_ivNew c sharp3_features_(linq)_part_iv
New c sharp3_features_(linq)_part_iv
 
The GO programming language
The GO programming languageThe GO programming language
The GO programming language
 
03 expressions.ppt
03 expressions.ppt03 expressions.ppt
03 expressions.ppt
 

Mehr von Nico Ludwig

Mehr von Nico Ludwig (16)

Grundkurs fuer excel_part_v
Grundkurs fuer excel_part_vGrundkurs fuer excel_part_v
Grundkurs fuer excel_part_v
 
Grundkurs fuer excel_part_iv
Grundkurs fuer excel_part_ivGrundkurs fuer excel_part_iv
Grundkurs fuer excel_part_iv
 
Grundkurs fuer excel_part_iii
Grundkurs fuer excel_part_iiiGrundkurs fuer excel_part_iii
Grundkurs fuer excel_part_iii
 
Grundkurs fuer excel_part_ii
Grundkurs fuer excel_part_iiGrundkurs fuer excel_part_ii
Grundkurs fuer excel_part_ii
 
Grundkurs fuer excel_part_i
Grundkurs fuer excel_part_iGrundkurs fuer excel_part_i
Grundkurs fuer excel_part_i
 
(2) gui drawing
(2) gui drawing(2) gui drawing
(2) gui drawing
 
(2) gui drawing
(2) gui drawing(2) gui drawing
(2) gui drawing
 
(1) gui history_of_interactivity
(1) gui history_of_interactivity(1) gui history_of_interactivity
(1) gui history_of_interactivity
 
(1) gui history_of_interactivity
(1) gui history_of_interactivity(1) gui history_of_interactivity
(1) gui history_of_interactivity
 
New c sharp3_features_(linq)_part_iii
New c sharp3_features_(linq)_part_iiiNew c sharp3_features_(linq)_part_iii
New c sharp3_features_(linq)_part_iii
 
New c sharp3_features_(linq)_part_i
New c sharp3_features_(linq)_part_iNew c sharp3_features_(linq)_part_i
New c sharp3_features_(linq)_part_i
 
New c sharp3_features_(linq)_part_i
New c sharp3_features_(linq)_part_iNew c sharp3_features_(linq)_part_i
New c sharp3_features_(linq)_part_i
 
Review of c_sharp2_features_part_ii
Review of c_sharp2_features_part_iiReview of c_sharp2_features_part_ii
Review of c_sharp2_features_part_ii
 
(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_ii(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_ii
 
(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_ii(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_ii
 
(5) c sharp introduction_object_orientation_part_ii
(5) c sharp introduction_object_orientation_part_ii(5) c sharp introduction_object_orientation_part_ii
(5) c sharp introduction_object_orientation_part_ii
 

Kürzlich hochgeladen

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 

Kürzlich hochgeladen (20)

Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 

New c sharp4_features_part_ii

  • 1. 1 New C#4 Features – Part II Nico Ludwig (@ersatzteilchen)
  • 2. 2 TOC ● New C#4 Features – Part II – New generic Types of the BCL in Detail: Lazy<T> and Tuple<T, ...> – Generic Variance ● Sources: – Jon Skeet, CSharp in Depth – Chamond Liu, Smalltalk, Objects, Design
  • 3. 3 New generic BCL Types <NewGenericBCLTypes> TShows the type Lazy<T>, Tuples and structural comparison with Tuples and arrays.
  • 4. 4 Lazy<T> ● Lazy<T> provides simple support for deferred initialization. – Idiomatic usage as (encapsulated) field of a type. ● Lazy initialization w/ dctors as well as w/ initializer functions is supported. ● Threadsafe initialization is supported.
  • 5. 5 Tuples – Part I ● Tuples are known from functional programming as ad hoc data structure. – A Tuple is: Basically a list of values (called components) of possibly different static types. – They have been introduced to use F# APIs that make use of Tuples. – .Net Tuples are ordinary generic types, but can have any number of components. ● There are generic overloads for up to seven components. ● This limit can be overcome by cascading Tuples. ● Tuples vs. anonymous types: – Only Tuples (as static type) can be returned from methods and passed to methods. – Only anonymous types have semantic quality, Tuples are rather data containers. – Both override Equals() and GetHashCode() in order to express value semantics. – Both are immutable in C#. ● Slightly like Lisp's concept of cons-cells. ● As the Tuple-types are not sealed you could derive your own implementation containing extra behavior. - But that's questionable as you can't hide possibly unwanted information (like the ItemX-properties accessing the components). ● Tuples can't be XML serialized (this esp. includes that they don't have a dctor).
  • 6. 6 Tuples – Part II ● Pro: – Allow creating more composable APIs. ● As alternative to passing back results with out/ref. ● Also very handy as return type of anonymous functions (e.g. in TPL code). – Support structural comparison. ● New in .Net 4: arrays also implement IStructuralEquatable and IStructuralComparable explicitly. – Allow exploiting F# APIs that deal with Tuples. ● Contra: – As they have fixed property names, they have very limited semantics. ● Limit their usage to return types and parameter types. ● Understand and use them as data containers. – Can't be used in web service interfaces, as Tuples can not be accordingly serialized. ● Using of Tuples can be better than anonymous types, if you need to return the result of an anonymous function from an enclosing _named_ function! ● Tuples are fine to create fluent APIs, as they allow to get rid of ref and out parameters.
  • 7. 7 Consistency of Type Hierarchies: Covariance ● What does "consistency" mean? – The idea is to design type-safe type hierarchies with highly substitutable types. – The key to get this consistency is subtype or subclass based conformance. – (We'll discuss the Liskov Substitution Principle (LSP) on a high level here.) ● Example: Let's assume Birds that lay Eggs "consistently" with static typing: – If the type Bird lays an Egg, wouldn't a Bird's subtype lay a subtype of Egg? – E.g. the type Duck lays a DuckEgg; then the consistency is given like so: DuckEgg – Why is this consistent? Because in such an expression (no C#!): + Lay : Egg Egg anEgg = aBird.Lay() Bird the reference aBird could be legally substituted by a Bird or by a Duck instance. – We say the return type is covariant to the type, in which Lay() is defined. – A subtype's override may return a more specialized type. => "They deliver more." Duck + Lay : DuckEgg Egg ● The term sub typing is used here a little sloppy. Virtually the terms sub typing and sub classing have different meanings when discussing substitutability, but the difference is not relevant here. ● The LSP was introduced by Prof. (MIT) Barbara Liskov in 1987. ● Covariance is esp. handy on abstract factories. ● Exception specifications in C++ and Java are also covariant (as they are similar to return types). ● Covariance/contravariance are terms taken from the mathematical "category theory" that deals with the substitution principle.
  • 8. 8 Consistency of Type Hierarchies: Contravariance ● Let's assume Pianos that Pianists can play "consistently" with static typing: – If a Pianist plays Piano, would she be able to play aGrandPiano? – Wouldn't rather a Virtuoso play a GrandPiano? (Be warned; there is a twist!) Virtuoso – This is inconsistent! Because in such an expression (no C#): + Play(player : Pianist) aPiano.Play(aPianist) Piano – aPiano couldn't be legally substituted by a Piano or by a GrandPiano instance! A GrandPiano can only be played by a Virtuoso, Pianists are too general! – GrandPianos must be playable by more general types, then the play is consistent: – We say the parameter type is contravariant to the type, in which Play() is defined. – A subtype's override may accept a more generalized type. => "They require less." GrandPiano + Play(player : Virtuoso) Pianist Pianist Piano + Play(player : Pianist) GrandPiano + Play(player : Person) Person ● The described conformance (covariant return types/contravariant parameter types) is the theoretical ideal (supported by the languages Emerald and POOL-1). Some oop languages (e.g. Eiffel) decided to apply another type of consistency, esp. also covariant parameter types, because it better describes the reality than the theoretical ideal. ● In statically typed languages the desired consistency must often be achieved by application of design patterns like "double dispatching" and "visitor". Other languages provide so-called "multiple dispatch" (e.g. CLOS) or get the desired effect by using dynamic typing.
  • 9. 9 Problems with covariant Arrays in C# <IntrinsicCSharpCovarianceWArrays> Shows the problem with covariance of arrays in C#.
  • 10. 10 Put the Consistency Theory into Practice with C#4 ● Variance expresses the consistency of type-safe type substitution. ● C# does already provide covariance on arrays. – Yes, it's not type-safe, but can we do anything more to reach better consistency? ● Yes, via generic variance available in C#4! – (But C#'s consistency is still based on invariant return and parameter types!) ● So, you can enable variances on generic delegate and interface types. – This feature was present since .Net 2, it was enabled for C# in C#4. – The idea is to define the variance of return and parameter types individually. – Different variances can be mixed in a specific delegate or interface. – With variance, the compiler will treat in and out - types differently, so that variant generic types act as if they were related. ● Covariance on arrays works only w/ reference conversions: inheritance and interface (of implicitly or explicitly implemented interfaces) conversions. (No boxing, value type or user conversions are allowed!) ● Try to limit the usage of array parameters to param-arrays, as they are much safer. ● In C# no covariant return types are available (in opposite to Java and C++). ● In C# methods with out and ref parameters are also not variant on that parameters. ● Variance can only be declared on generic interfaces and delegates, not on classes or structs. => It does not work without explicitly refactoring type hierarchies.
  • 11. 11 Generic Interface Variance in Action <CSharpCovariance> This example shows generic interface variance in C#. ● No example dealing with generic variance on delegates will be presented here. But you can find some examples in the source code accompanying this presentation.
  • 12. 12 Summary: generic Variance ● What is generic interface/delegate variance? – It allows "reasonable" implicit conversions between unrelated types to occur. ● So the main features variance enables are co- and contravariant conversions. – It reduces the amount of compile time errors. ● But only reference conversions of return and parameter types can be used! – (As with array covariance: no boxing, value type or user conversions are allowed!) ● Possibly you'll never code own variant types, but you'll exploit existing ones. – Some .Net types have been made variant: IEnumerable<out T>/IEnumerator<out T>, IComparable<in T>, Action<in T, ...>, Func<out T, in R, ..>, Converter<in T, out R>. ● Pitfalls with variant types: – New implicit conversions are in avail: type checks and overloads behave differently. – Generic variance on delegates does not work with multicasting. ● Example application: return types of factory interfaces. ● Reference conversions: inheritance and interface (of implicitly or explicitly implemented interfaces) conversions. ● .Net collection types must stay invariant as they use the same parametrized type for return and parameter values. ● The problem with multicasting might be fixed with a future .Net version. ● Before generic variance was enabled with C#4 there was a way to simulate covariance (see: http://blogs.msdn.com/b/kcwalina/archive/2008/0 4/02/simulatedcovariance.aspx ).
  • 13. 13 Variance "Mechanics" ● Expressing generic variance on interfaces: interface IFactory<out T> { // Covariant on T. T Produce(); } ● Expressing generic variance on delegates: // Covariant on T. delegate T Func<out T>(); ● Restrictions on expressing generic variance: – Only interface and delegate variance is supported. interface IAcceptor<in T> { // Contravariant on T. void Accept(T t); } // Contravariant on T. delegate void Action<in T>(T t); – Due to guaranteed static type-safety, return types can only be covariant and parameter types can only be contravariant! ● You have to declare the variance on the type parameters explicitly! ● You can not express your own consistency, esp. no consistency can be expressed on exceptions. – If T is a return type and a parameter type that type must be invariant. – out method parameters are always invariant, as they are CLR ref parameters! ● The C# compiler could, at least in most cases, infer the right variances; but you have to declare variances explicitly, because it might lead to breaking code. ● Since exceptions are not part of signatures in C#, no consistency can be declared on them. ● Because out method parameters can also be used to pass data to a method they can not be safely covariant as return types. The CLR does not make a difference between out and ref parameters. ● In Java, variances are expressed on the caller side of the (generic) type, i.e. nothing must be declared on the type itself to act variant. - C# uses statically checked definition-site variance (so does Scala). ● In dynamic languages the consistency is often present intrinsically, because substitutability is not expressed by static types, but by common interfaces (read: couple of methods). - Subtyping instead of subclassing is used here: more on this in following lectures. ● The IL syntax uses the symbols +/-T to denote the type of variance (the Scala syntax is similar).