SlideShare a Scribd company logo
1 
(7) Introduction of C# Basics – Advanced Features 
– Part II 
Nico Ludwig (@ersatzteilchen)
2 
TOC 
● (7) Introduction of C# – Advanced Features – Part II 
– Object-based and generic Collections 
– Delegates and Events 
– Custom Attributes 
– Reflection
3 
Collections 
● Collections are types that represent a set of other objects (elements or items). 
– Certain Collections differ in the way they manage access to their items. 
– Roughly we tell sequential from associative Collections. 
– Examples from namespace System.Collections: ArrayList, Hashtable, Queue or Stack. 
● .Net collections manage references to objects, not the objects itself. 
– Value type objects are being boxed into objects, when they are added. 
● object-based Collections are not typesafe! 
– One can easily introduce run time errors.
4 
Type Problems in Collections 
// A collection of Objects (the static type of those is System.Object). 
ArrayList aList = new ArrayList(); 
// One can add any type of Object into this collection. 
aList.Add(new Bus()); 
// If we want to access the contained object's interface, we have probably 
// to cast down to the dynamic type's interface. 
object anObject = aList[0]; 
VintageCar aVintageCar = (VintageCar)anObject; 
//... but we can fail here, e.g. if the actual dynamic type differs from the 
// assumed dynamic type. -> Bus is a System.Object, but not a VintageCar! 
// This cast will end in an InvalidCastException! 
// We'll never reach this line: 
double estimatedPrize = aVintageCar.EstimatedPrize;
5 
Generic Collections to the Rescue 
● Generic collections allow to specify the type of the managed items. 
– They live in the namespace System.Collections.Generic. 
– A type name is used as argument for a generic type. 
– The type names are specified in angle brackets: List<int> -> a list of int. 
● Arrays act also like generic collections, but employ another syntax. 
● Benefits compared to object-typed Collections: 
– With generic types the compiler can check typesafety. 
– Downcasting is not required. 
● It is also possible to create own generic types: 
– Generic classes, interfaces etc. 
– The range of allowed generic types can be controlled with constraints.
6 
Generic Collections in Action 
// A collection of VintageCars (static type). 
List<VintageCar> aList = new List<VintageCar>(42); 
// We can add any type of VintageCar into this collection. 
aList.Add(new VintageCar()); 
// We can not add Cars, this is a too common type. 
aList.Add(new Car()); // Compile time error 
// We can not add Buses, this type is no kind of VintageCar. 
aList.Add(new Bus()); // Compile time error 
// If we want to access the contained object's interface, 
// downcasting is not required, the assignment can not fail. 
VintageCar aVintageCar = aList[0]; 
double estimatedPrize = aVintageCar.EstimatedPrize;
7 
Delegates 
● Often there exist root-algorithms that call other sub-algorithms. 
– The root-algorithm is always identical. 
– Only the sub-algorithms are a matter of change. 
– Example: The root-algorithm "Sort" has a fix structure, but it calls compare-algorithms to compare objects. For each object type 
the compare-algorithm is probably different. 
● The idea of root- and sub-algorithms make up some kind of "template". 
– Root-algorithms such as "Sort" have a fix structure, the sub-algorithms vary. 
– For sub-algorithms, interfaces must be defined that fit into that "template". 
● .Net introduces the delegate concept to describe the interface of sub-algorithms in a type save manner. 
– In C/C++ we have a similar the concept with function pointers.
8 
Example of Almost identical Algorithms 
public void SortInts(List<int> elements) { 
for (int x = 0; x < elements.Count - 1; ++x) { 
for (int y = 0; y < elements.Count - 1 - x; ++y) { 
if (elements[y] > elements[y + 1]) 
{ 
Swap(y, y + 1, elements); 
} 
} 
} 
} 
public void SortStrings(List<string> elements) { 
for (int x = 0; x < elements.Count - 1; ++x) { 
for (int y = 0; y < elements.Count - 1 - x; ++y) { 
if (0 < string.Compare(elements[y], elements[y + 1])) 
{ 
Swap(y, y + 1, elements); 
} 
} 
} 
}
9 
Steps to improve the SortXXX Methods 
● The comparison expression is the only difference in the implementations! 
● Extract this sub-algorithm as method and define its signature as delegate: 
public delegate int Compare<T>(T left, T right); 
● Sort() gets passed a parameter of delegate type that represents a Compare() method implementation. 
● Within Sort() the passed delegate is invoked and its returned value is analyzed. 
– I.e. we'll pass another method as argument to the method Sort(). 
● In effect, the method Sort() is much more useful: it can sort any kinds of objects! 
– The programmer has to define a suitable Compare() method. 
– The Compare() method's identifier must be passed as argument.
10 
The same Algorithm with Delegates 
// Definition of the signature of delegate methods: 
public delegate int Compare<T>(T left, T right); 
// Definition of the "template" algorithm: 
public void Sort<T>(List<T> elements, Compare<T> cmp) 
{ 
for (int x = 0; x < elements.Count - 1; ++x) 
{ 
for (int y = 0; y < elements.Count - 1 - x; ++y) 
{ 
// Here the delegate is called: 
if (0 < cmp(elements[y], elements[y + 1])) 
{ 
Swap(y, y + 1, elements); 
} 
} 
} 
}
11 
Delegates in Action 
public static void Main(string[] args) { 
List<string> sList = new List<string>(2); 
sList.Add("World"); 
sList.Add("Hello"); 
List<int> iList = new List<int>(2); 
iList.Add(2); 
iList.Add(17); 
// Here the method identifiers are passed as arguments, the Compare- 
// operation is delegated to these methods. 
Sort<string>(sList, CompareStrings); 
Sort<int>(iList, CompareInts); 
} 
// Two methods with the signature of the delegate Compare: 
public int CompareStrings(string s1, string s2) { 
return string.Compare(s1, s2); 
} 
public int CompareInts(int i1, int i2) { 
return i1.CompareTo(i2); 
}
12 
Events 
● Sometimes it is useful to get notified, when an object's state is updated. 
– E.g. in Cars a notification when the Tank is almost empty is useful. 
● Such notifications are implemented as events in the .Net framework. 
– Syntactically events are special fields within a type that can refer to functions. 
● Observers register to events: 
– Registering to an event means to register a delegate instance to an event. 
– E.g. the Driver object can register to Car's event TankEmpty to get notified. 
– More than one observer can register to the event TankEmpty (multicasting). 
● Observed objects can raise events: 
– The event's type is a delegate that will be invoked from within the object. 
– On raising the event, arguments can be passed as well.
13 
Class Car with the Event TankEmpty 
// Define the delegate type for the event handler: 
public delegate void TankEmptyEventHandler(string info); 
public class Car { 
// Define the event TankEmpty like a field in Car: 
public event TankEmptyEventHandler TankEmpty; 
public void EngineRunning() { 
if (_tankRunningEmpty && null != TankEmpty) { 
// Raise the event: 
TankEmpty("Tank less than 5L!"); 
} 
} 
}
14 
Events in Action 
// Two methods that may act as handler for TankEmpty event instances of 
// TankEmptyEventHandler. 
public static void ReportToConsole(string info) { 
public static void Main(string[] args) { 
Car car = new Car(); // Object car is being observed here. 
// Register the two handlers (use operator -= to unregister). When the 
// event is raised these two handlers (the observers) are being called. 
car.TankEmpty += ReportToConsole; 
car.TankEmpty += DashBoardSignal; 
while (true) { 
car.EngineRunning(); 
} 
} 
Console.WriteLine(info); 
} 
public static void DashBoardSignal(string info) { 
TankEmptySignal.Set(true); 
}
15 
Custom Attributes 
● In C# .Net types and members can be annotated with C# attributes. 
– E.g.: private, sealed or readonly. 
● Custom attributes allow to add more metadata for a .Net element into IL. 
– Declarative nature: A type's behavior is modified without modifying the type itself. 
– Consumption: During run time this metadata can be read and interpreted via reflection. 
● There exist many predefined run time and compile time custom attributes. 
– Examples: FlagsAttribute, ConditionalAttribute, TestAttribute 
– How to annotate: Custom attributes can be placed via direct or targeted syntax. 
● Programmers can also define custom attributes. 
– Custom attributes have to derive from System.Attribute.
16 
Compile Time Attribute “Conditional” in Action 
public class Debug 
{ 
// The method WriteLine is annotated with ConditionalAttribute("DEBUG"): 
[System.Diagnostics.Conditional("DEBUG")] 
public static void WriteLine(string message) { /*pass */ } 
} 
private void F() 
{ 
// Due to the compile time ConditionalAttribute("DEBUG"), this method 
// call is only compiled in the "DEBUG" configuration: 
System.Diagnostics.Debug.WriteLine("Hello out there!"); 
}
17 
Reflection 
● The .Net framework allows to analyze types during run time via reflection. 
● Reflection is needed: 
– If code must handle unknown types (members, hierarchies etc.). 
● This was addressed with dynamic typing in .Net 4 as well. 
– If code has to decide upon type features. 
● E.g., if code has to analyze custom attributes. 
● Reflection is accessible via the type Type and the namespace System.Reflection. 
● Reflection should be used sparingly, because it is rather expensive. 
– Better use polymorphism and design patterns.
18 
Reflecting Type "String" 
public void Main() { 
// Getting the type of String to start reflection: 
Type theStringType = typeof(string); 
// Reflecting all custom attributes (also the inherited ones) of the type string: 
object[] customAttributes = theStringType.GetCustomAttributes(true); 
for (int i = 0; i < customAttributes.Length; ++i) { 
Attribute attribute = (Attribute)customAttributes[i]; 
Console.WriteLine(attribute); 
} 
// Reflecting all methods of the type String: 
object[] methods = theStringType.GetMethods(); 
for (int i = 0; i < methods.Length; ++i) { 
System.Reflection.MethodInfo methodInfo = (System.Reflection.MethodInfo)methods[i]; 
Console.WriteLine(methodInfo); 
} 
}
19 
C# Features not Covered in this Course 
● Operator overloading and user defined indexers. 
● Generics in depth. 
● Nullable types. 
● Iterators and yielding. 
● LINQ and Lambda expressions. 
● Dynamic typing. 
● Programming of: (Web)Services, (Web)Applications with GUI and Concurrent code.
20 
Thank you!

More Related Content

What's hot

(4) collections algorithms
(4) collections algorithms(4) collections algorithms
(4) collections algorithms
Nico Ludwig
 
Qcon2011 functions rockpresentation_f_sharp
Qcon2011 functions rockpresentation_f_sharpQcon2011 functions rockpresentation_f_sharp
Qcon2011 functions rockpresentation_f_sharp
Michael Stal
 
Storage classess of C progamming
Storage classess of C progamming Storage classess of C progamming
Storage classess of C progamming
Appili Vamsi Krishna
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scala
Michael Stal
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation Stal
Michael Stal
 
Programming with Lambda Expressions in Java
Programming with Lambda Expressions in Java Programming with Lambda Expressions in Java
Programming with Lambda Expressions in Java
langer4711
 
Storage classes in C
Storage classes in CStorage classes in C
Storage classes in C
Nitesh Bichwani
 
ParaSail
ParaSail  ParaSail
ParaSail
AdaCore
 
C sharp part 001
C sharp part 001C sharp part 001
C sharp part 001
Ralph Weber
 
Java 8 - Project Lambda
Java 8 - Project LambdaJava 8 - Project Lambda
Java 8 - Project Lambda
Rahman USTA
 
Functions in c
Functions in cFunctions in c
Functions in c
SunithaVesalpu
 
Storage classes in C
Storage classes in C Storage classes in C
Storage classes in C
Self employed
 
Storage class
Storage classStorage class
Storage class
Joy Forerver
 
Java 8 lambda
Java 8 lambdaJava 8 lambda
Java 8 lambda
Manav Prasad
 
Storage class in c
Storage class in cStorage class in c
Storage class in c
kash95
 
11 lec 11 storage class
11 lec 11 storage class11 lec 11 storage class
11 lec 11 storage classkapil078
 

What's hot (20)

(4) collections algorithms
(4) collections algorithms(4) collections algorithms
(4) collections algorithms
 
Savitch Ch 18
Savitch Ch 18Savitch Ch 18
Savitch Ch 18
 
Qcon2011 functions rockpresentation_f_sharp
Qcon2011 functions rockpresentation_f_sharpQcon2011 functions rockpresentation_f_sharp
Qcon2011 functions rockpresentation_f_sharp
 
Storage classess of C progamming
Storage classess of C progamming Storage classess of C progamming
Storage classess of C progamming
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scala
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation Stal
 
Programming with Lambda Expressions in Java
Programming with Lambda Expressions in Java Programming with Lambda Expressions in Java
Programming with Lambda Expressions in Java
 
Storage classes in C
Storage classes in CStorage classes in C
Storage classes in C
 
ParaSail
ParaSail  ParaSail
ParaSail
 
C sharp part 001
C sharp part 001C sharp part 001
C sharp part 001
 
Java 8 - Project Lambda
Java 8 - Project LambdaJava 8 - Project Lambda
Java 8 - Project Lambda
 
Operators & Casts
Operators & CastsOperators & Casts
Operators & Casts
 
Storage class in C Language
Storage class in C LanguageStorage class in C Language
Storage class in C Language
 
Functions in c
Functions in cFunctions in c
Functions in c
 
Storage classes in C
Storage classes in C Storage classes in C
Storage classes in C
 
Storage class
Storage classStorage class
Storage class
 
Java 8 lambda
Java 8 lambdaJava 8 lambda
Java 8 lambda
 
Storage class in c
Storage class in cStorage class in c
Storage class in c
 
11 lec 11 storage class
11 lec 11 storage class11 lec 11 storage class
11 lec 11 storage class
 
Managed Compiler
Managed CompilerManaged Compiler
Managed Compiler
 

Similar to (7) c sharp introduction_advanvced_features_part_ii

(3) cpp procedural programming
(3) cpp procedural programming(3) cpp procedural programming
(3) cpp procedural programming
Nico Ludwig
 
Generic Programming seminar
Generic Programming seminarGeneric Programming seminar
Generic Programming seminarGautam Roy
 
Gude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic ServerGude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic Server
Apache Traffic Server
 
(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
 
Wien15 java8
Wien15 java8Wien15 java8
Wien15 java8
Jaanus Pöial
 
Java 8 Streams
Java 8 StreamsJava 8 Streams
Java 8 Streams
Manvendra Singh
 
Unit iii
Unit iiiUnit iii
Unit iii
snehaarao19
 
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
 
(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
 
Java8: what's new and what's hot
Java8: what's new and what's hotJava8: what's new and what's hot
Java8: what's new and what's hot
Sergii Maliarov
 
UNIT III (2).ppt
UNIT III (2).pptUNIT III (2).ppt
UNIT III (2).ppt
VGaneshKarthikeyan
 
UNIT III.ppt
UNIT III.pptUNIT III.ppt
UNIT III.ppt
Ajit Mali
 
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
Akaks
 
A Brief Conceptual Introduction to Functional Java 8 and its API
A Brief Conceptual Introduction to Functional Java 8 and its APIA Brief Conceptual Introduction to Functional Java 8 and its API
A Brief Conceptual Introduction to Functional Java 8 and its API
Jörn Guy Süß JGS
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentation
Van Huong
 
Java 8
Java 8Java 8
Java 8
vilniusjug
 
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
 
Goal The goal of this assignment is to help students understand the.pdf
Goal The goal of this assignment is to help students understand the.pdfGoal The goal of this assignment is to help students understand the.pdf
Goal The goal of this assignment is to help students understand the.pdf
arsmobiles
 
(7) cpp abstractions inheritance_part_ii
(7) cpp abstractions inheritance_part_ii(7) cpp abstractions inheritance_part_ii
(7) cpp abstractions inheritance_part_ii
Nico Ludwig
 

Similar to (7) c sharp introduction_advanvced_features_part_ii (20)

(3) cpp procedural programming
(3) cpp procedural programming(3) cpp procedural programming
(3) cpp procedural programming
 
Generic Programming seminar
Generic Programming seminarGeneric Programming seminar
Generic Programming seminar
 
Gude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic ServerGude for C++11 in Apache Traffic Server
Gude for C++11 in Apache Traffic Server
 
(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
 
Wien15 java8
Wien15 java8Wien15 java8
Wien15 java8
 
Java 8 Streams
Java 8 StreamsJava 8 Streams
Java 8 Streams
 
Unit iii
Unit iiiUnit iii
Unit iii
 
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
 
(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
 
Java8: what's new and what's hot
Java8: what's new and what's hotJava8: what's new and what's hot
Java8: what's new and what's hot
 
UNIT III (2).ppt
UNIT III (2).pptUNIT III (2).ppt
UNIT III (2).ppt
 
UNIT III.ppt
UNIT III.pptUNIT III.ppt
UNIT III.ppt
 
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
 
A Brief Conceptual Introduction to Functional Java 8 and its API
A Brief Conceptual Introduction to Functional Java 8 and its APIA Brief Conceptual Introduction to Functional Java 8 and its API
A Brief Conceptual Introduction to Functional Java 8 and its API
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentation
 
java8
java8java8
java8
 
Java 8
Java 8Java 8
Java 8
 
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
 
Goal The goal of this assignment is to help students understand the.pdf
Goal The goal of this assignment is to help students understand the.pdfGoal The goal of this assignment is to help students understand the.pdf
Goal The goal of this assignment is to help students understand the.pdf
 
(7) cpp abstractions inheritance_part_ii
(7) cpp abstractions inheritance_part_ii(7) cpp abstractions inheritance_part_ii
(7) cpp abstractions inheritance_part_ii
 

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 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_v
New c sharp4_features_part_vNew c sharp4_features_part_v
New c sharp4_features_part_v
Nico Ludwig
 
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
 
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
 
New c sharp4_features_part_ii
New c sharp4_features_part_iiNew c sharp4_features_part_ii
New c sharp4_features_part_ii
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
 
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
 
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
 
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_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_ii
New c sharp3_features_(linq)_part_iiNew c sharp3_features_(linq)_part_ii
New c sharp3_features_(linq)_part_ii
Nico Ludwig
 

More from 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_ii
New c sharp4_features_part_iiNew c sharp4_features_part_ii
New c sharp4_features_part_ii
 
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_v
New c sharp3_features_(linq)_part_vNew c sharp3_features_(linq)_part_v
New c sharp3_features_(linq)_part_v
 
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_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_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_ii
New c sharp3_features_(linq)_part_iiNew c sharp3_features_(linq)_part_ii
New c sharp3_features_(linq)_part_ii
 

Recently uploaded

FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
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
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
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
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
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
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Aggregage
 
Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.
ViralQR
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Paige Cruz
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Nexer Digital
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
Vlad Stirbu
 
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
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 

Recently uploaded (20)

FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
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...
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
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
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
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 !
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
 
Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfObservability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdf
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?Elizabeth Buie - Older adults: Are we really designing for our future selves?
Elizabeth Buie - Older adults: Are we really designing for our future selves?
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
 
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
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 

(7) c sharp introduction_advanvced_features_part_ii

  • 1. 1 (7) Introduction of C# Basics – Advanced Features – Part II Nico Ludwig (@ersatzteilchen)
  • 2. 2 TOC ● (7) Introduction of C# – Advanced Features – Part II – Object-based and generic Collections – Delegates and Events – Custom Attributes – Reflection
  • 3. 3 Collections ● Collections are types that represent a set of other objects (elements or items). – Certain Collections differ in the way they manage access to their items. – Roughly we tell sequential from associative Collections. – Examples from namespace System.Collections: ArrayList, Hashtable, Queue or Stack. ● .Net collections manage references to objects, not the objects itself. – Value type objects are being boxed into objects, when they are added. ● object-based Collections are not typesafe! – One can easily introduce run time errors.
  • 4. 4 Type Problems in Collections // A collection of Objects (the static type of those is System.Object). ArrayList aList = new ArrayList(); // One can add any type of Object into this collection. aList.Add(new Bus()); // If we want to access the contained object's interface, we have probably // to cast down to the dynamic type's interface. object anObject = aList[0]; VintageCar aVintageCar = (VintageCar)anObject; //... but we can fail here, e.g. if the actual dynamic type differs from the // assumed dynamic type. -> Bus is a System.Object, but not a VintageCar! // This cast will end in an InvalidCastException! // We'll never reach this line: double estimatedPrize = aVintageCar.EstimatedPrize;
  • 5. 5 Generic Collections to the Rescue ● Generic collections allow to specify the type of the managed items. – They live in the namespace System.Collections.Generic. – A type name is used as argument for a generic type. – The type names are specified in angle brackets: List<int> -> a list of int. ● Arrays act also like generic collections, but employ another syntax. ● Benefits compared to object-typed Collections: – With generic types the compiler can check typesafety. – Downcasting is not required. ● It is also possible to create own generic types: – Generic classes, interfaces etc. – The range of allowed generic types can be controlled with constraints.
  • 6. 6 Generic Collections in Action // A collection of VintageCars (static type). List<VintageCar> aList = new List<VintageCar>(42); // We can add any type of VintageCar into this collection. aList.Add(new VintageCar()); // We can not add Cars, this is a too common type. aList.Add(new Car()); // Compile time error // We can not add Buses, this type is no kind of VintageCar. aList.Add(new Bus()); // Compile time error // If we want to access the contained object's interface, // downcasting is not required, the assignment can not fail. VintageCar aVintageCar = aList[0]; double estimatedPrize = aVintageCar.EstimatedPrize;
  • 7. 7 Delegates ● Often there exist root-algorithms that call other sub-algorithms. – The root-algorithm is always identical. – Only the sub-algorithms are a matter of change. – Example: The root-algorithm "Sort" has a fix structure, but it calls compare-algorithms to compare objects. For each object type the compare-algorithm is probably different. ● The idea of root- and sub-algorithms make up some kind of "template". – Root-algorithms such as "Sort" have a fix structure, the sub-algorithms vary. – For sub-algorithms, interfaces must be defined that fit into that "template". ● .Net introduces the delegate concept to describe the interface of sub-algorithms in a type save manner. – In C/C++ we have a similar the concept with function pointers.
  • 8. 8 Example of Almost identical Algorithms public void SortInts(List<int> elements) { for (int x = 0; x < elements.Count - 1; ++x) { for (int y = 0; y < elements.Count - 1 - x; ++y) { if (elements[y] > elements[y + 1]) { Swap(y, y + 1, elements); } } } } public void SortStrings(List<string> elements) { for (int x = 0; x < elements.Count - 1; ++x) { for (int y = 0; y < elements.Count - 1 - x; ++y) { if (0 < string.Compare(elements[y], elements[y + 1])) { Swap(y, y + 1, elements); } } } }
  • 9. 9 Steps to improve the SortXXX Methods ● The comparison expression is the only difference in the implementations! ● Extract this sub-algorithm as method and define its signature as delegate: public delegate int Compare<T>(T left, T right); ● Sort() gets passed a parameter of delegate type that represents a Compare() method implementation. ● Within Sort() the passed delegate is invoked and its returned value is analyzed. – I.e. we'll pass another method as argument to the method Sort(). ● In effect, the method Sort() is much more useful: it can sort any kinds of objects! – The programmer has to define a suitable Compare() method. – The Compare() method's identifier must be passed as argument.
  • 10. 10 The same Algorithm with Delegates // Definition of the signature of delegate methods: public delegate int Compare<T>(T left, T right); // Definition of the "template" algorithm: public void Sort<T>(List<T> elements, Compare<T> cmp) { for (int x = 0; x < elements.Count - 1; ++x) { for (int y = 0; y < elements.Count - 1 - x; ++y) { // Here the delegate is called: if (0 < cmp(elements[y], elements[y + 1])) { Swap(y, y + 1, elements); } } } }
  • 11. 11 Delegates in Action public static void Main(string[] args) { List<string> sList = new List<string>(2); sList.Add("World"); sList.Add("Hello"); List<int> iList = new List<int>(2); iList.Add(2); iList.Add(17); // Here the method identifiers are passed as arguments, the Compare- // operation is delegated to these methods. Sort<string>(sList, CompareStrings); Sort<int>(iList, CompareInts); } // Two methods with the signature of the delegate Compare: public int CompareStrings(string s1, string s2) { return string.Compare(s1, s2); } public int CompareInts(int i1, int i2) { return i1.CompareTo(i2); }
  • 12. 12 Events ● Sometimes it is useful to get notified, when an object's state is updated. – E.g. in Cars a notification when the Tank is almost empty is useful. ● Such notifications are implemented as events in the .Net framework. – Syntactically events are special fields within a type that can refer to functions. ● Observers register to events: – Registering to an event means to register a delegate instance to an event. – E.g. the Driver object can register to Car's event TankEmpty to get notified. – More than one observer can register to the event TankEmpty (multicasting). ● Observed objects can raise events: – The event's type is a delegate that will be invoked from within the object. – On raising the event, arguments can be passed as well.
  • 13. 13 Class Car with the Event TankEmpty // Define the delegate type for the event handler: public delegate void TankEmptyEventHandler(string info); public class Car { // Define the event TankEmpty like a field in Car: public event TankEmptyEventHandler TankEmpty; public void EngineRunning() { if (_tankRunningEmpty && null != TankEmpty) { // Raise the event: TankEmpty("Tank less than 5L!"); } } }
  • 14. 14 Events in Action // Two methods that may act as handler for TankEmpty event instances of // TankEmptyEventHandler. public static void ReportToConsole(string info) { public static void Main(string[] args) { Car car = new Car(); // Object car is being observed here. // Register the two handlers (use operator -= to unregister). When the // event is raised these two handlers (the observers) are being called. car.TankEmpty += ReportToConsole; car.TankEmpty += DashBoardSignal; while (true) { car.EngineRunning(); } } Console.WriteLine(info); } public static void DashBoardSignal(string info) { TankEmptySignal.Set(true); }
  • 15. 15 Custom Attributes ● In C# .Net types and members can be annotated with C# attributes. – E.g.: private, sealed or readonly. ● Custom attributes allow to add more metadata for a .Net element into IL. – Declarative nature: A type's behavior is modified without modifying the type itself. – Consumption: During run time this metadata can be read and interpreted via reflection. ● There exist many predefined run time and compile time custom attributes. – Examples: FlagsAttribute, ConditionalAttribute, TestAttribute – How to annotate: Custom attributes can be placed via direct or targeted syntax. ● Programmers can also define custom attributes. – Custom attributes have to derive from System.Attribute.
  • 16. 16 Compile Time Attribute “Conditional” in Action public class Debug { // The method WriteLine is annotated with ConditionalAttribute("DEBUG"): [System.Diagnostics.Conditional("DEBUG")] public static void WriteLine(string message) { /*pass */ } } private void F() { // Due to the compile time ConditionalAttribute("DEBUG"), this method // call is only compiled in the "DEBUG" configuration: System.Diagnostics.Debug.WriteLine("Hello out there!"); }
  • 17. 17 Reflection ● The .Net framework allows to analyze types during run time via reflection. ● Reflection is needed: – If code must handle unknown types (members, hierarchies etc.). ● This was addressed with dynamic typing in .Net 4 as well. – If code has to decide upon type features. ● E.g., if code has to analyze custom attributes. ● Reflection is accessible via the type Type and the namespace System.Reflection. ● Reflection should be used sparingly, because it is rather expensive. – Better use polymorphism and design patterns.
  • 18. 18 Reflecting Type "String" public void Main() { // Getting the type of String to start reflection: Type theStringType = typeof(string); // Reflecting all custom attributes (also the inherited ones) of the type string: object[] customAttributes = theStringType.GetCustomAttributes(true); for (int i = 0; i < customAttributes.Length; ++i) { Attribute attribute = (Attribute)customAttributes[i]; Console.WriteLine(attribute); } // Reflecting all methods of the type String: object[] methods = theStringType.GetMethods(); for (int i = 0; i < methods.Length; ++i) { System.Reflection.MethodInfo methodInfo = (System.Reflection.MethodInfo)methods[i]; Console.WriteLine(methodInfo); } }
  • 19. 19 C# Features not Covered in this Course ● Operator overloading and user defined indexers. ● Generics in depth. ● Nullable types. ● Iterators and yielding. ● LINQ and Lambda expressions. ● Dynamic typing. ● Programming of: (Web)Services, (Web)Applications with GUI and Concurrent code.

Editor's Notes

  1. Another perception of generic types/Collections: They define a structure and some or all data types in that structure may change.
  2. Mind that the differences between both algorithms are very small.
  3. The definition of a Delegate type looks a little bit like a typedef in C/C++. According Compare&amp;lt;T&amp;gt;(): What is the meaning of the T?
  4. Events are like interrupts. What are interrupts? Interrupts are interrupting &amp;quot;notifications&amp;quot; issued by the hardware, e.g. I/O. What are alternative techniques? Primarily &amp;quot;polling&amp;quot;. Polling means to use software to ask for new events periodically.
  5. The methods ReportToConsole() and DashBoardSignal() are the event handlers. Sometimes such methods are called &amp;quot;callback functions&amp;quot;. Callback functions implement what we call the &amp;quot;Hollywood principle&amp;quot;: &amp;quot;Don&amp;apos;t call us, we&amp;apos;ll call you!&amp;quot;, they are also an incarnation of the &amp;quot;Inversion of Control” paradigm.
  6. We want to analyze (reflect) the type System.String. (A good German word for reflection is &amp;quot;Selbstauskunft&amp;quot;.) Iterate over its custom attributes. Iterate over its methods.