SlideShare ist ein Scribd-Unternehmen logo
1 von 14
Downloaden Sie, um offline zu lesen
1 
Review of C#2 Features – Part III 
Nico Ludwig (@ersatzteilchen)
2 
TOC 
● Review of C#2 Features – Part III 
– Iterators 
– Nullable Types 
● Sources: 
– Jon Skeet, CSharp in Depth
3 
Iterator Support in C#1 
● "Iterator" is one of the simplest (behavioral) Design Patterns. 
– The aim of iterator is to separate the Collection from the item access. 
– Not all items of a Collection are fetched, but only the current item. 
● In .Net "iterator" is represented by the interface IEnumerator/<T>. 
– (This matches to COM's IEnumXXX interfaces directly.) 
– Iterator allows to program concise forward loops with an unknown end condition. 
– In C# usage, one encounters them when using Collections on foreach loops. 
– (During iteration the Collection and the current item are generally mutation guarded!) 
● But it is relatively hard to write new iterators in C#1, e.g. to support foreach. 
– It is required to implement IEnumerable/IEnumerator in userdefined types. 
– It is recommended to implement them in two classes to separate responsibilities. 
– A few methods must be written and the state (the current item) must be maintained. 
● In C# most known programming patterns are only 
supported indirectly, i.e. they can be implemented 
in C# easily. Few patterns are supported by 
dedicated language features, iterator is one of 
these patterns. 
● We're going to discuss the iterator pattern in .Net. 
● An object implementing IEnumerator/<T> is called 
iterator, or cursor or enumerator object. 
● Extra benefit: Iterators are good to avoid off-by-one 
errors: there is no index.
4 
Guts of the foreach Loop unveiled 
<ForeachExample> 
Expresses a foreach loop with a while loop to show the 
usage of iterators. 
● C#'s iterator terms: 
● An object implementing IEnumerable/<T> is 
called sequence or enumerable object. 
● An object implementing IEnumerator/<T> is 
called iterator or enumerator object. Iterators are 
returned by a sequence's method 
GetEnumerator(). I.e. multiple iterators can 
correspond to a sequence. In database terms: 
IEnumerable/<T> is a table and 
IEnumerator/<T> is a cursor.
5 
The C#2 Way to provide Iterators 
● Wrap up: The target is to support foreach in user defined types somehow. 
● In C#2 the new contextual keyword yield allows easy iterator implementation. 
– Indeed, this idea is not new, it is almost literally taken from Ruby/Python. 
● How this simple iterator is used: 
– The iterator block is a method that returns IEnumerator/<T> or IEnumerable/<T> and uses the keyword yield (generally) in a loop 
to create the resulting sequence. 
– Iterator blocks enable deferred execution: no line of code in the body of the iterator block runs until the first call to MoveNext() is 
performed. 
– yield return puts the current item (of the loop) into the sequence (IEnumerable/<T>). 
– yield break terminates the iteration. 
● A C#2 compiler creates classes implementingIEnumerator/<T> and IEnumerable/<T>. 
● Iterator blocks are similar to so-called coroutines. 
Coroutines are a way to pass the execution control to 
another block af code and then return to the original 
execution point. It can be simulated by multiple threads 
or by other ways to store the original stackframe. In 
generated C# code: the status of the coroutine is 
stored on the stack as status and a switch statement 
acts on that status on each call of MoveNext(). 
● In C# an object being returned from an iterator block is 
called sequence or enumerable object if it is an 
IEnumerable/<T>. If the returned object is an 
IEnumerator/<T> it is called iterator or enumerator 
object in C#. 
● (Btw.: Do not implement both IEnumerator/IEnumerable 
on the same type!) 
● Within an iterator block a simple return is not allowed, 
but it can have multiple yield returns/breaks. 
● It is also possible to implement a recursive iterator 
block or w/o any loop!
6 
C#2 Iterators in Action 
<IteratorExamples> 
Presents examples of generator functions to produce 
sequences. 
● A method returning an IEnumerable/<T> or IEnumerable/<T> 
is called iterator block when it uses one or many yield 
statements. 
● Iterator blocks implement a state machine: 
● In opposite to an ordinary return statement the yield return 
statement seams only to temporarily step out and pause the 
method. 
● They are a form of continuation or coroutine or fibre (last in 
the programming language D, where the stackpointers will 
be really switched). 
● They enable deferred execution: no line of code in the body 
of the iterator block runs until the first call to MoveNext(). 
● The code of the finally blocks in iterator blocks will be 
executed: 
● when the iterator block leaves execution, or 
● when a yield break statement is executed, or 
● when the iterator will be disposed of, which is done by 
foreach automatically.
7 
Some Words on C#2 Iterators 
● This easy way to implement and think about iterators is very powerful: 
– Iterators are not limited to "collection-iteration", one can work w/o collections. 
– (E.g. you can implement iterator blocks as properties! - But that's not wise.) 
– Possibility to implement infinite mathematical sets and sequences directly from iteration. 
– Possibility to defer the calculation of data until they're really needed. 
● Gotcha: Using generator IEnumerable to replace returning of Collections. 
– The IEnumerable/<T> is generated every time the generator function is called/iterated! 
– Framework guideline: use methods returning iterators and properties returning collections. 
● Gotcha: The mutation guard during foreach/iteration may not be checked. 
– It must be implemented manually if required. 
● C#2 iterators are an important basis for "LINQ to Objects" in C#3. 
● Anonymous methods can not be iterator blocks. It 
was counted to be too much effort for the C# 
compiler team. 
● Only top level methods can be iterator blocks. 
● Anonymous iterator blocks are supported in 
VB11! 
● For similar reasons methods with out or ref 
parameters can not be iterator blocks.
8 
Lack of Nullity for Value Types 
● Value types cannot have no value. 
– A value type can at least have a default value (this is an incarnation of 0 or false). 
– On the other hand reference types are allowed to have no value, via null. 
● Sometimes it is desirable to have nullable value types. 
– E.g. as seen on databases, where values of primitive type can be NULL. 
– So on doing database ORM with C# similar requirements arise as well. 
● To simulate "no value" for value types there exist some patterns in C#1: 
– Sacrifice a sentinel value to express "no value", e.g. -1, DateTime.MinValue ... 
– Box the value type into a reference type, so null expresses "no value" again. 
– Add a boolean flag for the value type to indicate “no value”. 
● In C#2 the last pattern has been promoted to a language feature.
9 
Introducing the Type Nullable<T> 
● C#2 provides the type Nullable<T> and syntactic sugar to provide nullity. 
<NullableExample> 
Presents examples of the usage of type Nullable<T>.
10 
.Net 2 Support for Nullity 
● Having a Nullable<T> instance, null is a value, not a null-reference any longer! 
● Defined as struct Nullable<T>, where T must be a value type. 
– Nullable<T> is itself a value type! (I.e. locally created on stack, boxable etc.) 
– T is called the underlying type. 
– The property HasValue checks, whether the value type has a value (is not null). 
– The property Value allows to access the wrapped value type's value, though. 
– The method GetHashCode() returns 0, if the value has no value. 
– The method Equals() returns false, if one operand is null or unequal the other operand. 
● The static class Nullable provides further tool methods: 
static class Nullable { // (members hidden) 
int Compare<T>(Nullable<T>, Nullable<T>); 
bool Equals<T>(Nullable<T>, Nullable<T>); 
Type GetUnderlyingType(Type nullableType); 
} 
● Equals/Compare<T>() use 
EqualityComparer/Comparer<T>.Default, which 
returns IEqualityComparer<T>. If T implements 
IEquateable<T> (which is most efficient in most 
cases, it calls its generic Equals<T>()), or it 
returns the default implementation that makes use 
of Object's virtual Equals() (causing boxing) and 
GetHashCode().
11 
C#2 Support for Nullity 
● In addition to the syntax Nullable<T> C#2 allows the more concise syntax T?. 
Nullable<int> <=> int? 
● T? allows the usage of operators by lifting them from the underlying type! 
– Lifting: For most operators of T, operators with T?-operands/results are generated. 
– E.g. for arithmetic and bitwise operators of T?: If any operand is null the result is null. 
● T's operators need to obey following restrictions for lifting: 
– Only operands with non-nullable types get lifted, return types must be non-nullable. 
– The return type of equality and relational operators must be bool. 
– (The operators true and false get never lifted.) 
– (Yes, this looks complicated, but everything works as expected.) 
● Additionally C#2 provides extra logical operators for bool? (i.e. "treebool"). 
– The operators | and & provide logic here, not ||/&& (they aren't allowed on bool?). 
● Lifting of operators when Nullables are used, 
results in more robust code, as null-values don't 
harm anymore. But lifting can also be confusing! 
● More features of Nullables in the attached 
example code: 
● The boxing behavior of nullables is special. 
When a Nullable<T> is boxed the wrapped type 
T will be boxed, not the "whole" Nullable<T>. 
● The as-operator can be used for reference types 
and for boxed value types as Nullables. 
● Following the .Net Framework Desgin Guidelines 
nullable value type should also be used instead of 
otherwise special types like System.DBNull.
12 
The Null Coalescing Operator 
● C#2 provides the null coalescing operator ?? to compact syntax. 
– It can be understood as conditional operator (?:) for nullity in C#. 
– This operator is binary, but right associative and cannot be overloaded. 
– It can be used for Nullable<T> and any reference type. 
– Good to write defaulting or fall-back patterns.
13 
Not discussed Features new in C#2 
● Primarily for code generation: 
– Partial types 
– Namespace aliases 
– #pragma checksum 
● #pragma warning (disable|restore) 
● fixed buffers in unsafe code 
● Friend assemblies 
● CLR 2: 
– Support for 64 bit processors (x86 and IA64). 
– CLR hosting within SQL Server 2005. 
● The new feature "partial types" (for classes, 
structs and interfaces) are intended to part a type 
into multiple separate files to better handle 
generated code. Some files (typically one) 
contains the IDE-generated code, the other files 
can be edited by the programmer. It is e.g. used 
in the Forms API. 
● The #pragma directives are instructions to the 
compiler. The Microsoft compiler understands the 
#pragmas warning and checksum. In future 
versions of the compiler other #pragmas, or 
compiler-vendor specific #pragmas could be 
provided. Unknown #pragmas will be ignored by 
the compiler.
14 
14 
Thank you!

Weitere ähnliche Inhalte

Was ist angesagt? (20)

What is storage class
What is storage classWhat is storage class
What is storage class
 
Java New Programming Features
Java New Programming FeaturesJava New Programming Features
Java New Programming Features
 
Storage classes in C
Storage classes in CStorage classes in C
Storage classes in C
 
Kotlin compiler construction (very brief)
Kotlin compiler construction (very brief)Kotlin compiler construction (very brief)
Kotlin compiler construction (very brief)
 
(4) collections algorithms
(4) collections algorithms(4) collections algorithms
(4) collections algorithms
 
C interview questions
C interview  questionsC interview  questions
C interview questions
 
Developer’s viewpoint on swift programming language
Developer’s viewpoint on swift programming languageDeveloper’s viewpoint on swift programming language
Developer’s viewpoint on swift programming language
 
Constructors and destructors in C++ part 2
Constructors and destructors in C++ part 2Constructors and destructors in C++ part 2
Constructors and destructors in C++ part 2
 
Lecture 1
Lecture 1Lecture 1
Lecture 1
 
Storage class in C Language
Storage class in C LanguageStorage class in C Language
Storage class in C Language
 
Storage Class in C Progrmming
Storage Class in C Progrmming Storage Class in C Progrmming
Storage Class in C Progrmming
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
 
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
 
Core java concepts
Core java concepts Core java concepts
Core java concepts
 
Operators in java
Operators in javaOperators in java
Operators in java
 
Swift Programming
Swift ProgrammingSwift Programming
Swift Programming
 
Virtual Function
Virtual FunctionVirtual Function
Virtual Function
 
Storage classes in C
Storage classes in C Storage classes in C
Storage classes in C
 
Storage classes
Storage classesStorage classes
Storage classes
 
C language ppt
C language pptC language ppt
C language ppt
 

Andere mochten auch

Ppoint Tocas Tiago
Ppoint Tocas TiagoPpoint Tocas Tiago
Ppoint Tocas TiagoTocasTiago
 
Celebración Día de Africa en el Bioparc
Celebración Día de Africa en el BioparcCelebración Día de Africa en el Bioparc
Celebración Día de Africa en el Bioparcfunmainel
 
Ppoint Tocas Tiago
Ppoint Tocas TiagoPpoint Tocas Tiago
Ppoint Tocas TiagoTocasTiago
 
Paper id 25201442
Paper id 25201442Paper id 25201442
Paper id 25201442IJRAT
 

Andere mochten auch (6)

Week 4
Week 4Week 4
Week 4
 
Tocas Tiago
Tocas TiagoTocas Tiago
Tocas Tiago
 
Ppoint Tocas Tiago
Ppoint Tocas TiagoPpoint Tocas Tiago
Ppoint Tocas Tiago
 
Celebración Día de Africa en el Bioparc
Celebración Día de Africa en el BioparcCelebración Día de Africa en el Bioparc
Celebración Día de Africa en el Bioparc
 
Ppoint Tocas Tiago
Ppoint Tocas TiagoPpoint Tocas Tiago
Ppoint Tocas Tiago
 
Paper id 25201442
Paper id 25201442Paper id 25201442
Paper id 25201442
 

Ähnlich wie Review of c_sharp2_features_part_iii

New c sharp3_features_(linq)_part_iii
New c sharp3_features_(linq)_part_iiiNew c sharp3_features_(linq)_part_iii
New c sharp3_features_(linq)_part_iiiNico Ludwig
 
(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_iiNico Ludwig
 
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_iNico Ludwig
 
(3) cpp procedural programming
(3) cpp procedural programming(3) cpp procedural programming
(3) cpp procedural programmingNico 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-stringsNico Ludwig
 
New c sharp4_features_part_ii
New c sharp4_features_part_iiNew c sharp4_features_part_ii
New c sharp4_features_part_iiNico Ludwig
 
Python coroutine
Python coroutinePython coroutine
Python coroutine경섭 심
 
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
 
New c sharp3_features_(linq)_part_i
New c sharp3_features_(linq)_part_iNew c sharp3_features_(linq)_part_i
New c sharp3_features_(linq)_part_iNico Ludwig
 
(2) cpp imperative programming
(2) cpp imperative programming(2) cpp imperative programming
(2) cpp imperative programmingNico Ludwig
 
New c sharp3_features_(linq)_part_ii
New c sharp3_features_(linq)_part_iiNew c sharp3_features_(linq)_part_ii
New c sharp3_features_(linq)_part_iiNico Ludwig
 
1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answersAkash Gawali
 
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
 
C++ Interview Question And Answer
C++ Interview Question And AnswerC++ Interview Question And Answer
C++ Interview Question And AnswerJagan Mohan Bishoyi
 
C++ questions And Answer
C++ questions And AnswerC++ questions And Answer
C++ questions And Answerlavparmar007
 
(2) cpp imperative programming
(2) cpp imperative programming(2) cpp imperative programming
(2) cpp imperative programmingNico Ludwig
 
New microsoft office word document (2)
New microsoft office word document (2)New microsoft office word document (2)
New microsoft office word document (2)rashmita_mishra
 
classVII_Coding_Teacher_Presentation.pptx
classVII_Coding_Teacher_Presentation.pptxclassVII_Coding_Teacher_Presentation.pptx
classVII_Coding_Teacher_Presentation.pptxssusere336f4
 
Exploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App developmentExploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App developmentJayaprakash R
 

Ähnlich wie Review of c_sharp2_features_part_iii (20)

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
 
(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
 
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
 
(3) cpp procedural programming
(3) cpp procedural programming(3) cpp procedural programming
(3) cpp procedural programming
 
(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
 
New c sharp4_features_part_ii
New c sharp4_features_part_iiNew c sharp4_features_part_ii
New c sharp4_features_part_ii
 
Python coroutine
Python coroutinePython coroutine
Python coroutine
 
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#)
 
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
 
(2) cpp imperative programming
(2) cpp imperative programming(2) cpp imperative programming
(2) cpp imperative programming
 
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
 
1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers
 
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
 
C++ Interview Question And Answer
C++ Interview Question And AnswerC++ Interview Question And Answer
C++ Interview Question And Answer
 
C++ questions And Answer
C++ questions And AnswerC++ questions And Answer
C++ questions And Answer
 
(2) cpp imperative programming
(2) cpp imperative programming(2) cpp imperative programming
(2) cpp imperative programming
 
New microsoft office word document (2)
New microsoft office word document (2)New microsoft office word document (2)
New microsoft office word document (2)
 
85ec7 session2 c++
85ec7 session2 c++85ec7 session2 c++
85ec7 session2 c++
 
classVII_Coding_Teacher_Presentation.pptx
classVII_Coding_Teacher_Presentation.pptxclassVII_Coding_Teacher_Presentation.pptx
classVII_Coding_Teacher_Presentation.pptx
 
Exploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App developmentExploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App development
 

Mehr von Nico Ludwig

Grundkurs fuer excel_part_v
Grundkurs fuer excel_part_vGrundkurs fuer excel_part_v
Grundkurs fuer excel_part_vNico Ludwig
 
Grundkurs fuer excel_part_iv
Grundkurs fuer excel_part_ivGrundkurs fuer excel_part_iv
Grundkurs fuer excel_part_ivNico Ludwig
 
Grundkurs fuer excel_part_iii
Grundkurs fuer excel_part_iiiGrundkurs fuer excel_part_iii
Grundkurs fuer excel_part_iiiNico Ludwig
 
Grundkurs fuer excel_part_ii
Grundkurs fuer excel_part_iiGrundkurs fuer excel_part_ii
Grundkurs fuer excel_part_iiNico Ludwig
 
Grundkurs fuer excel_part_i
Grundkurs fuer excel_part_iGrundkurs fuer excel_part_i
Grundkurs fuer excel_part_iNico Ludwig
 
(1) gui history_of_interactivity
(1) gui history_of_interactivity(1) gui history_of_interactivity
(1) gui history_of_interactivityNico Ludwig
 
(1) gui history_of_interactivity
(1) gui history_of_interactivity(1) gui history_of_interactivity
(1) gui history_of_interactivityNico Ludwig
 
New c sharp4_features_part_vi
New c sharp4_features_part_viNew c sharp4_features_part_vi
New c sharp4_features_part_viNico Ludwig
 
New c sharp4_features_part_v
New c sharp4_features_part_vNew c sharp4_features_part_v
New c sharp4_features_part_vNico Ludwig
 
New c sharp4_features_part_iv
New c sharp4_features_part_ivNew c sharp4_features_part_iv
New c sharp4_features_part_ivNico Ludwig
 
New c sharp4_features_part_iii
New c sharp4_features_part_iiiNew c sharp4_features_part_iii
New c sharp4_features_part_iiiNico Ludwig
 
New c sharp4_features_part_i
New c sharp4_features_part_iNew c sharp4_features_part_i
New c sharp4_features_part_iNico Ludwig
 
New c sharp3_features_(linq)_part_iv
New c sharp3_features_(linq)_part_ivNew c sharp3_features_(linq)_part_iv
New c sharp3_features_(linq)_part_ivNico Ludwig
 
New c sharp3_features_(linq)_part_i
New c sharp3_features_(linq)_part_iNew c sharp3_features_(linq)_part_i
New c sharp3_features_(linq)_part_iNico 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_iiNico 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_iNico 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_iNico 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_iiNico Ludwig
 

Mehr von Nico Ludwig (20)

Grundkurs fuer excel_part_v
Grundkurs fuer excel_part_vGrundkurs fuer excel_part_v
Grundkurs fuer excel_part_v
 
Grundkurs fuer excel_part_iv
Grundkurs fuer excel_part_ivGrundkurs fuer excel_part_iv
Grundkurs fuer excel_part_iv
 
Grundkurs fuer excel_part_iii
Grundkurs fuer excel_part_iiiGrundkurs fuer excel_part_iii
Grundkurs fuer excel_part_iii
 
Grundkurs fuer excel_part_ii
Grundkurs fuer excel_part_iiGrundkurs fuer excel_part_ii
Grundkurs fuer excel_part_ii
 
Grundkurs fuer excel_part_i
Grundkurs fuer excel_part_iGrundkurs fuer excel_part_i
Grundkurs fuer excel_part_i
 
(2) gui drawing
(2) gui drawing(2) gui drawing
(2) gui drawing
 
(2) gui drawing
(2) gui drawing(2) gui drawing
(2) gui drawing
 
(1) gui history_of_interactivity
(1) gui history_of_interactivity(1) gui history_of_interactivity
(1) gui history_of_interactivity
 
(1) gui history_of_interactivity
(1) gui history_of_interactivity(1) gui history_of_interactivity
(1) gui history_of_interactivity
 
New c sharp4_features_part_vi
New c sharp4_features_part_viNew c sharp4_features_part_vi
New c sharp4_features_part_vi
 
New c sharp4_features_part_v
New c sharp4_features_part_vNew c sharp4_features_part_v
New c sharp4_features_part_v
 
New c sharp4_features_part_iv
New c sharp4_features_part_ivNew c sharp4_features_part_iv
New c sharp4_features_part_iv
 
New c sharp4_features_part_iii
New c sharp4_features_part_iiiNew c sharp4_features_part_iii
New c sharp4_features_part_iii
 
New c sharp4_features_part_i
New c sharp4_features_part_iNew c sharp4_features_part_i
New c sharp4_features_part_i
 
New c sharp3_features_(linq)_part_iv
New c sharp3_features_(linq)_part_ivNew c sharp3_features_(linq)_part_iv
New c sharp3_features_(linq)_part_iv
 
New c sharp3_features_(linq)_part_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
 
(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
 
(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
 
(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

Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
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...Miguel Araújo
 
[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.pdfhans926745
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
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 2024The Digital Insurer
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
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 MenDelhi Call girls
 
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.pptxEarley 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 Servicegiselly40
 

Kürzlich hochgeladen (20)

Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
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...
 
[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
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
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
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
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
 
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
 
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
 

Review of c_sharp2_features_part_iii

  • 1. 1 Review of C#2 Features – Part III Nico Ludwig (@ersatzteilchen)
  • 2. 2 TOC ● Review of C#2 Features – Part III – Iterators – Nullable Types ● Sources: – Jon Skeet, CSharp in Depth
  • 3. 3 Iterator Support in C#1 ● "Iterator" is one of the simplest (behavioral) Design Patterns. – The aim of iterator is to separate the Collection from the item access. – Not all items of a Collection are fetched, but only the current item. ● In .Net "iterator" is represented by the interface IEnumerator/<T>. – (This matches to COM's IEnumXXX interfaces directly.) – Iterator allows to program concise forward loops with an unknown end condition. – In C# usage, one encounters them when using Collections on foreach loops. – (During iteration the Collection and the current item are generally mutation guarded!) ● But it is relatively hard to write new iterators in C#1, e.g. to support foreach. – It is required to implement IEnumerable/IEnumerator in userdefined types. – It is recommended to implement them in two classes to separate responsibilities. – A few methods must be written and the state (the current item) must be maintained. ● In C# most known programming patterns are only supported indirectly, i.e. they can be implemented in C# easily. Few patterns are supported by dedicated language features, iterator is one of these patterns. ● We're going to discuss the iterator pattern in .Net. ● An object implementing IEnumerator/<T> is called iterator, or cursor or enumerator object. ● Extra benefit: Iterators are good to avoid off-by-one errors: there is no index.
  • 4. 4 Guts of the foreach Loop unveiled <ForeachExample> Expresses a foreach loop with a while loop to show the usage of iterators. ● C#'s iterator terms: ● An object implementing IEnumerable/<T> is called sequence or enumerable object. ● An object implementing IEnumerator/<T> is called iterator or enumerator object. Iterators are returned by a sequence's method GetEnumerator(). I.e. multiple iterators can correspond to a sequence. In database terms: IEnumerable/<T> is a table and IEnumerator/<T> is a cursor.
  • 5. 5 The C#2 Way to provide Iterators ● Wrap up: The target is to support foreach in user defined types somehow. ● In C#2 the new contextual keyword yield allows easy iterator implementation. – Indeed, this idea is not new, it is almost literally taken from Ruby/Python. ● How this simple iterator is used: – The iterator block is a method that returns IEnumerator/<T> or IEnumerable/<T> and uses the keyword yield (generally) in a loop to create the resulting sequence. – Iterator blocks enable deferred execution: no line of code in the body of the iterator block runs until the first call to MoveNext() is performed. – yield return puts the current item (of the loop) into the sequence (IEnumerable/<T>). – yield break terminates the iteration. ● A C#2 compiler creates classes implementingIEnumerator/<T> and IEnumerable/<T>. ● Iterator blocks are similar to so-called coroutines. Coroutines are a way to pass the execution control to another block af code and then return to the original execution point. It can be simulated by multiple threads or by other ways to store the original stackframe. In generated C# code: the status of the coroutine is stored on the stack as status and a switch statement acts on that status on each call of MoveNext(). ● In C# an object being returned from an iterator block is called sequence or enumerable object if it is an IEnumerable/<T>. If the returned object is an IEnumerator/<T> it is called iterator or enumerator object in C#. ● (Btw.: Do not implement both IEnumerator/IEnumerable on the same type!) ● Within an iterator block a simple return is not allowed, but it can have multiple yield returns/breaks. ● It is also possible to implement a recursive iterator block or w/o any loop!
  • 6. 6 C#2 Iterators in Action <IteratorExamples> Presents examples of generator functions to produce sequences. ● A method returning an IEnumerable/<T> or IEnumerable/<T> is called iterator block when it uses one or many yield statements. ● Iterator blocks implement a state machine: ● In opposite to an ordinary return statement the yield return statement seams only to temporarily step out and pause the method. ● They are a form of continuation or coroutine or fibre (last in the programming language D, where the stackpointers will be really switched). ● They enable deferred execution: no line of code in the body of the iterator block runs until the first call to MoveNext(). ● The code of the finally blocks in iterator blocks will be executed: ● when the iterator block leaves execution, or ● when a yield break statement is executed, or ● when the iterator will be disposed of, which is done by foreach automatically.
  • 7. 7 Some Words on C#2 Iterators ● This easy way to implement and think about iterators is very powerful: – Iterators are not limited to "collection-iteration", one can work w/o collections. – (E.g. you can implement iterator blocks as properties! - But that's not wise.) – Possibility to implement infinite mathematical sets and sequences directly from iteration. – Possibility to defer the calculation of data until they're really needed. ● Gotcha: Using generator IEnumerable to replace returning of Collections. – The IEnumerable/<T> is generated every time the generator function is called/iterated! – Framework guideline: use methods returning iterators and properties returning collections. ● Gotcha: The mutation guard during foreach/iteration may not be checked. – It must be implemented manually if required. ● C#2 iterators are an important basis for "LINQ to Objects" in C#3. ● Anonymous methods can not be iterator blocks. It was counted to be too much effort for the C# compiler team. ● Only top level methods can be iterator blocks. ● Anonymous iterator blocks are supported in VB11! ● For similar reasons methods with out or ref parameters can not be iterator blocks.
  • 8. 8 Lack of Nullity for Value Types ● Value types cannot have no value. – A value type can at least have a default value (this is an incarnation of 0 or false). – On the other hand reference types are allowed to have no value, via null. ● Sometimes it is desirable to have nullable value types. – E.g. as seen on databases, where values of primitive type can be NULL. – So on doing database ORM with C# similar requirements arise as well. ● To simulate "no value" for value types there exist some patterns in C#1: – Sacrifice a sentinel value to express "no value", e.g. -1, DateTime.MinValue ... – Box the value type into a reference type, so null expresses "no value" again. – Add a boolean flag for the value type to indicate “no value”. ● In C#2 the last pattern has been promoted to a language feature.
  • 9. 9 Introducing the Type Nullable<T> ● C#2 provides the type Nullable<T> and syntactic sugar to provide nullity. <NullableExample> Presents examples of the usage of type Nullable<T>.
  • 10. 10 .Net 2 Support for Nullity ● Having a Nullable<T> instance, null is a value, not a null-reference any longer! ● Defined as struct Nullable<T>, where T must be a value type. – Nullable<T> is itself a value type! (I.e. locally created on stack, boxable etc.) – T is called the underlying type. – The property HasValue checks, whether the value type has a value (is not null). – The property Value allows to access the wrapped value type's value, though. – The method GetHashCode() returns 0, if the value has no value. – The method Equals() returns false, if one operand is null or unequal the other operand. ● The static class Nullable provides further tool methods: static class Nullable { // (members hidden) int Compare<T>(Nullable<T>, Nullable<T>); bool Equals<T>(Nullable<T>, Nullable<T>); Type GetUnderlyingType(Type nullableType); } ● Equals/Compare<T>() use EqualityComparer/Comparer<T>.Default, which returns IEqualityComparer<T>. If T implements IEquateable<T> (which is most efficient in most cases, it calls its generic Equals<T>()), or it returns the default implementation that makes use of Object's virtual Equals() (causing boxing) and GetHashCode().
  • 11. 11 C#2 Support for Nullity ● In addition to the syntax Nullable<T> C#2 allows the more concise syntax T?. Nullable<int> <=> int? ● T? allows the usage of operators by lifting them from the underlying type! – Lifting: For most operators of T, operators with T?-operands/results are generated. – E.g. for arithmetic and bitwise operators of T?: If any operand is null the result is null. ● T's operators need to obey following restrictions for lifting: – Only operands with non-nullable types get lifted, return types must be non-nullable. – The return type of equality and relational operators must be bool. – (The operators true and false get never lifted.) – (Yes, this looks complicated, but everything works as expected.) ● Additionally C#2 provides extra logical operators for bool? (i.e. "treebool"). – The operators | and & provide logic here, not ||/&& (they aren't allowed on bool?). ● Lifting of operators when Nullables are used, results in more robust code, as null-values don't harm anymore. But lifting can also be confusing! ● More features of Nullables in the attached example code: ● The boxing behavior of nullables is special. When a Nullable<T> is boxed the wrapped type T will be boxed, not the "whole" Nullable<T>. ● The as-operator can be used for reference types and for boxed value types as Nullables. ● Following the .Net Framework Desgin Guidelines nullable value type should also be used instead of otherwise special types like System.DBNull.
  • 12. 12 The Null Coalescing Operator ● C#2 provides the null coalescing operator ?? to compact syntax. – It can be understood as conditional operator (?:) for nullity in C#. – This operator is binary, but right associative and cannot be overloaded. – It can be used for Nullable<T> and any reference type. – Good to write defaulting or fall-back patterns.
  • 13. 13 Not discussed Features new in C#2 ● Primarily for code generation: – Partial types – Namespace aliases – #pragma checksum ● #pragma warning (disable|restore) ● fixed buffers in unsafe code ● Friend assemblies ● CLR 2: – Support for 64 bit processors (x86 and IA64). – CLR hosting within SQL Server 2005. ● The new feature "partial types" (for classes, structs and interfaces) are intended to part a type into multiple separate files to better handle generated code. Some files (typically one) contains the IDE-generated code, the other files can be edited by the programmer. It is e.g. used in the Forms API. ● The #pragma directives are instructions to the compiler. The Microsoft compiler understands the #pragmas warning and checksum. In future versions of the compiler other #pragmas, or compiler-vendor specific #pragmas could be provided. Unknown #pragmas will be ignored by the compiler.
  • 14. 14 14 Thank you!