SlideShare a Scribd company logo
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!

More Related Content

What's hot

Clean code
Clean codeClean code
Clean code
Nascenia IT
 
F# for Scala developers
F# for Scala developersF# for Scala developers
F# for Scala developers
Alfonso Garcia-Caro
 
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
Randy Scovil
 
Learn C# Programming - Variables & Constants
Learn C# Programming - Variables & ConstantsLearn C# Programming - Variables & Constants
Learn C# Programming - Variables & Constants
Eng Teong Cheah
 
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
Ayushman Jain
 
Why functional programming in C# & F#
Why functional programming in C# & F#Why functional programming in C# & F#
Why functional programming in C# & F#
Riccardo Terrell
 
Switch statement
Switch statementSwitch statement
Switch statement
Patrick John McGee
 
Coding style of Linux Kernel
Coding style of Linux KernelCoding style of Linux Kernel
Coding style of Linux KernelPeter Chang
 
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
Mozaic Works
 
(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
Nico Ludwig
 
Looping and switch cases
Looping and switch casesLooping and switch cases
Looping and switch casesMeoRamos
 
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)
Jonathan Holloway
 
Master in javascript
Master in javascriptMaster in javascript
Master in javascript
Robbin Zhao
 
C++ c#
C++ c#C++ c#
C++ c#
Sireesh K
 
Theperlreview
TheperlreviewTheperlreview
Theperlreview
Casiano Rodriguez-leon
 
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
Pratik Khasnabis
 
Integers pointers | By Vikram Snehi
Integers pointers | By Vikram SnehiIntegers pointers | By Vikram Snehi
Integers pointers | By Vikram Snehi
MR. VIKRAM SNEHI
 
Grooming with Groovy
Grooming with GroovyGrooming with Groovy
Grooming with Groovy
Dhaval Dalal
 

What's hot (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
 

Viewers also liked

New c sharp4_features_part_v
New c sharp4_features_part_vNew c sharp4_features_part_v
New c sharp4_features_part_v
Nico Ludwig
 
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
 
New c sharp4_features_part_vi
New c sharp4_features_part_viNew c sharp4_features_part_vi
New c sharp4_features_part_vi
Nico Ludwig
 
New c sharp4_features_part_iii
New c sharp4_features_part_iiiNew c sharp4_features_part_iii
New c sharp4_features_part_iii
Nico Ludwig
 
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
CHOOSE
 
New c sharp4_features_part_iv
New c sharp4_features_part_ivNew c sharp4_features_part_iv
New c sharp4_features_part_iv
Nico Ludwig
 
Introduction to F#x
Introduction to F#xIntroduction to F#x
Introduction to F#x
Ryan Riley
 
Introduction to Reactive Extensions
Introduction to Reactive ExtensionsIntroduction to Reactive Extensions
Introduction to Reactive ExtensionsPeter Goodman
 
Reactive Extensions
Reactive ExtensionsReactive Extensions
Reactive ExtensionsKiev ALT.NET
 
Pertemuan 1. introduction to image processing
Pertemuan 1. introduction to image processingPertemuan 1. introduction to image processing
Pertemuan 1. introduction to image processingAditya Kurniawan
 
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
Nico Ludwig
 
F:\Universidad Tecnologica Israel
F:\Universidad Tecnologica IsraelF:\Universidad Tecnologica Israel
F:\Universidad Tecnologica Israel
santiago
 
Introduction To Csharp
Introduction To CsharpIntroduction To Csharp
Introduction To Csharpsarfarazali
 
The Power of F#
The Power of F#The Power of F#
The Power of F#
Isaac Abraham
 
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 MonadsRichard Minerich
 
Texas STaR
Texas STaRTexas STaR
Texas STaRllyarbro
 
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 2013Adam Mlocek
 

Viewers also liked (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
 

Similar to New c sharp4_features_part_ii

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
Nico Ludwig
 
(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
Nico Ludwig
 
Review of c_sharp2_features_part_iii
Review of c_sharp2_features_part_iiiReview of c_sharp2_features_part_iii
Review of c_sharp2_features_part_iii
Nico Ludwig
 
New c sharp3_features_(linq)_part_iv
New c sharp3_features_(linq)_part_ivNew c sharp3_features_(linq)_part_iv
New c sharp3_features_(linq)_part_ivNico Ludwig
 
(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
Nico Ludwig
 
(4) c sharp introduction_object_orientation_part_i
(4) c sharp introduction_object_orientation_part_i(4) c sharp introduction_object_orientation_part_i
(4) c sharp introduction_object_orientation_part_i
Nico Ludwig
 
(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
Nico Ludwig
 
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#)
Shoaib Ghachi
 
F# Intro for Scala Developers
F# Intro for Scala DevelopersF# Intro for Scala Developers
F# Intro for Scala Developers
fsug
 
Functional Programming in C# and F#
Functional Programming in C# and F#Functional Programming in C# and F#
Functional Programming in C# and F#
Alfonso Garcia-Caro
 
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
Nico Ludwig
 
(2) cpp imperative programming
(2) cpp imperative programming(2) cpp imperative programming
(2) cpp imperative programming
Nico Ludwig
 
New c sharp4_features_part_i
New c sharp4_features_part_iNew c sharp4_features_part_i
New c sharp4_features_part_i
Nico Ludwig
 
(3) cpp procedural programming
(3) cpp procedural programming(3) cpp procedural programming
(3) cpp procedural programming
Nico Ludwig
 
New c sharp3_features_(linq)_part_iv
New c sharp3_features_(linq)_part_ivNew c sharp3_features_(linq)_part_iv
New c sharp3_features_(linq)_part_iv
Nico Ludwig
 
The GO programming language
The GO programming languageThe GO programming language
The GO programming language
Marco Sabatini
 
03 expressions.ppt
03 expressions.ppt03 expressions.ppt
03 expressions.pptBusiness man
 

Similar to 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
 

More from Nico Ludwig

Grundkurs fuer excel_part_v
Grundkurs fuer excel_part_vGrundkurs fuer excel_part_v
Grundkurs fuer excel_part_v
Nico Ludwig
 
Grundkurs fuer excel_part_iv
Grundkurs fuer excel_part_ivGrundkurs fuer excel_part_iv
Grundkurs fuer excel_part_iv
Nico Ludwig
 
Grundkurs fuer excel_part_iii
Grundkurs fuer excel_part_iiiGrundkurs fuer excel_part_iii
Grundkurs fuer excel_part_iii
Nico Ludwig
 
Grundkurs fuer excel_part_ii
Grundkurs fuer excel_part_iiGrundkurs fuer excel_part_ii
Grundkurs fuer excel_part_ii
Nico Ludwig
 
Grundkurs fuer excel_part_i
Grundkurs fuer excel_part_iGrundkurs fuer excel_part_i
Grundkurs fuer excel_part_i
Nico Ludwig
 
(2) gui drawing
(2) gui drawing(2) gui drawing
(2) gui drawing
Nico Ludwig
 
(2) gui drawing
(2) gui drawing(2) gui drawing
(2) gui drawing
Nico Ludwig
 
(1) gui history_of_interactivity
(1) gui history_of_interactivity(1) gui history_of_interactivity
(1) gui history_of_interactivity
Nico Ludwig
 
(1) gui history_of_interactivity
(1) gui history_of_interactivity(1) gui history_of_interactivity
(1) gui history_of_interactivity
Nico Ludwig
 
New c sharp3_features_(linq)_part_iii
New c sharp3_features_(linq)_part_iiiNew c sharp3_features_(linq)_part_iii
New c sharp3_features_(linq)_part_iii
Nico Ludwig
 
New c sharp3_features_(linq)_part_i
New c sharp3_features_(linq)_part_iNew c sharp3_features_(linq)_part_i
New c sharp3_features_(linq)_part_i
Nico Ludwig
 
New c sharp3_features_(linq)_part_i
New c sharp3_features_(linq)_part_iNew c sharp3_features_(linq)_part_i
New c sharp3_features_(linq)_part_i
Nico Ludwig
 
Review of c_sharp2_features_part_ii
Review of c_sharp2_features_part_iiReview of c_sharp2_features_part_ii
Review of c_sharp2_features_part_ii
Nico Ludwig
 
(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_ii(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_ii
Nico Ludwig
 
(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_ii(7) c sharp introduction_advanvced_features_part_ii
(7) c sharp introduction_advanvced_features_part_ii
Nico Ludwig
 
(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
Nico Ludwig
 

More from 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
 

Recently uploaded

Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
g2nightmarescribd
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 

Recently uploaded (20)

Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 

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).