Www.itu.dk Advanced C#, part I Niels Hallenberg IT University of Copenhagen BAAAP – Spring 2009.

Slides:



Advertisements
Similar presentations
Generics, Lists, Interfaces
Advertisements

LINQ and Collections An introduction to LINQ and Collections.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 12 th -13 th Lecture Pavel Ježek.
1 Generic Collections Chapter Objectives You will be able to Use generic collection classes available in the.NET framework.
Java Review Interface, Casting, Generics, Iterator.
Copyright © 2012 Pearson Education, Inc. Chapter 9 Delegates and Events.
Generics and the ArrayList Class
ITEC200 – Week03 Inheritance and Class Hierarchies.
Collections. 2 Objectives Explore collections in System.Collections namespace –memory management –containment testing –sorting –traversal.
 2006 Pearson Education, Inc. All rights reserved Generics Many slides modified by Prof. L. Lilien (even many without an explicit message). Slides.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
Recommendation: Play the game and attempt to answer the questions yourself without looking at the answers. You’ll learn much less if you just look at the.
Chapter 14 Generics and the ArrayList Class Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
C# Programming: From Problem Analysis to Program Design1 Advanced Object-Oriented Programming Features C# Programming: From Problem Analysis to Program.
Cmp Sci 187: Midterm Review Based on Lecture Notes.
Subclasses and Subtypes CMPS Subclasses and Subtypes A class is a subclass if it has been built using inheritance. ▫ It says nothing about the meaning.
Differences between C# and C++ Dr. Catherine Stringfellow Dr. Stewart Carpenter.
OOP Languages: Java vs C++
Multiple Choice Solutions True/False a c b e d   T F.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Taken from slides of Starting Out with C++ Early Objects Seventh Edition.
FEN 2012UCN Technology - Computer Science 1 Data Structures and Collections Principles revisited.NET: –Two libraries: System.Collections System.Collections.Generics.
CS2110: SW Development Methods Textbook readings: MSD, Chapter 8 (Sect. 8.1 and 8.2) But we won’t implement our own, so study the section on Java’s Map.
CISC6795: Spring Object-Oriented Programming: Polymorphism.
Data Structures Using C++ 2E
BIM313 – Advanced Programming Techniques Object-Oriented Programming 1.
Copyright © 2006 Thomas P. Skinner1 Chapter 5 Indexers, Interfaces, and Enumerators.
Object Composition Interfaces Collections Covariance Object class Programming using C# LECTURE 10.
Generalized Containers CSIS 3701: Advanced Object Oriented Programming.
Programming Languages and Paradigms Object-Oriented Programming (Part II)
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called.
APCS Java AB 2004 Review of CS1 and CS2 Review for AP test #1 Sources: 2003 Workshop notes from Chris Nevison (Colgate University) AP Study Guide to go.
Generics Collections. Why do we need Generics? Another method of software re-use. When we implement an algorithm, we want to re-use it for different types.
Generics and Collections. Introduction Generics New feature of J2SE 5.0 Provide compile-time type safety Catch invalid types at compile time Generic methods.
Session 08 Module 14: Generics and Iterator Module 15: Anonymous & partial class & Nullable type.
Modern Software Development Using C#.NET Chapter 5: More Advanced Class Construction.
1/20/03A2-1 CS494 Interfaces and Collection in Java.
Generics Collections. Why do we need Generics? Another method of software re-use. When we implement an algorithm, we want to re-use it for different types.
Introduction to C#. Why C#? Develop on the Following Platforms ASP.NET Native Windows Windows 8 / 8.1 Windows Phone WPF Android (Xamarin) iOS (Xamarin)
Understanding Data Types and Collections Lesson 2.
Advanced C# Types Tom Roeder CS fa. From last time out parameters difference is that the callee is required to assign it before returning not the.
This recitation 1 An interesting point about A3: Using previous methods to avoid work in programming and debugging. How much time did you spend writing.
U n i v e r s i t y o f H a i l 1 ICS 202  2011 spring  Data Structures and Algorithms 
Introduction to C# 2.0 An Advanced Look Adam Calderon Principal Engineer - Interknowlogy Microsoft MVP – C#
PROGRAMMING IN C#. Collection Classes (C# Programming Guide) The.NET Framework provides specialized classes for data storage and retrieval. These classes.
Generics Generics vs. heterogeneous collections Doing your own generics FEN 2014UCN Teknologi/act2learn1.
Session 07 Module 13 - Collections. Collections / Session 7 / 2 of 32 Review  A delegate in C# is used to refer to a method in a safe manner.  To invoke.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Interfaces F What is an Interface? F Creating an Interface F Implementing an Interface F What is Marker Interface?
Object Oriented Software Development 6. Arrays and collections.
Data Structures and Collections Principles.NET: –Two libraries: System.Collections System.Collections.Generics FEN 2014UCN Teknologi/act2learn1 Deprecated.
Lecture 8: Advanced OOP Part 2. Overview Review of Subtypes Interfaces Packages Sorting.
COMPUTER PROGRAMMING 2 ArrayLists. Objective/Essential Standard Essential Standard 3.00Apply Advanced Properties of Arrays Essential Indicator 3.02 Apply.
Introduction to Collections. Collections Collections provide a way of organizing related data in a model Different types of collections have different.
1 Principles revisited.NET: Two libraries: System.Collections System.Collections.Generics Data Structures and Collections.
1 C# - Inheritance and Polymorphism. 2 1.Inheritance 2.Implementing Inheritance in C# 3.Constructor calls in Inheritance 4.Protected Access Modifier 5.The.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Part 1: Composition, Aggregation, and Delegation Part 2: Iterator COMP 401 Fall 2014 Lecture 10 9/18/2014.
Chapter  Array-like data structures  ArrayList  Queue  Stack  Hashtable  SortedList  Offer programming convenience for specific access.
Lecture 8: Collections, Comparisons and Conversions. Svetla Boytcheva AUBG, Spring COS 240 Object-Oriented Languages.
Module 5: Programming with C#. Overview Using Arrays Using Collections Using Interfaces Using Exception Handling Using Delegates and Events.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Computing with C# and the .NET Framework
Array Array is a variable which holds multiple values (elements) of similar data types. All the values are having their own index with an array. Index.
.NET and .NET Core 5.2 Type Operations Pan Wuming 2016.
CS313D: Advanced Programming Language
CIS 199 Final Review.
Java Programming Language
Defining Interfaces using C#
CMPE212 – Reminders Assignment 2 due next Friday.
Presentation transcript:

Advanced C#, part I Niels Hallenberg IT University of Copenhagen BAAAP – Spring 2009

Outline Advanced C#, Part I Interfaces Collections and Generics Delegates and Lanbdas For our project High Quality Test Data Stubs

Interfaces –Interfaces and Abstract Base Classes –What are Interfaces used for? You have a single hierarchy where only a subset of the derived types have a common behavior The same behavior must be implemented on types in different hierarchies with only the System.object as common parent class. Why do we need both? Functionality that must be supported by some type. You can’t enable four-wheel drive on all cars. Illustrated by many built in interfaces, fx IEnumerable, IEnumerator, ICloneable, ICompareable and IComparer

Single Hierarky Interface Abstract Vechicle class public abstract class Vechicle { int numWheels; String vechicleName; public Vechicle(int w, String n) { this.numWheels = w; this.vechicleName = n; } public override String ToString() { return "Vechicle " + this.vechicleName + …; } public abstract int numPersons(); } All sub classes must have a numPersons method.

Single Hierarky Interface The ILicenseNo interface public interface ILicenseNo { String LicenseNo {get; set;} } Some vechicles does have a license number

Single Hierarky Interface Cycle, Bike and Car classes public class Cycle : Vechicle { public Cycle() : base(2, "cycle") { } public override int numPersons() { return 1; } } public class Bike : Vechicle, ILicenseNo { private String licenseNo; public Bike(String licenseNo) : base(2, "bike") { this.licenseNo = licenseNo; } public String LicenseNo { get { return this.licenseNo; } set { this.licenseNo = value; } } public override int numPersons() { return 2; } } It’s a sports cycle. A Bike does have a license number Required by the interface Required by the Vechicle class

Single Hierarky Interface The Car class public class Car : Vechicle, ILicenseNo { String licenseNo; public Car(String licenseNo) : base(4, "car") { this.licenseNo = licenseNo; } public String LicenseNo { get { return this.licenseNo; } set { this.licenseNo = value; } } public override int numPersons() { return 4; } } A car does have a license number

Single Hierarky Interface Using the class hierarky Vechicle[] vs = { new Cycle(), new Bike("RX 34213"), new Car("GC 45221") }; // Print all vechicles foreach (Vechicle v in vs) Console.WriteLine(v.ToString() + " has " + v.numPersons() + " seats."); A bike and Car got a license number All vechicles can be pretty printed and got a number of persons. All sub-classes to Vechicle must implement numPersons. Using is and as. Console.WriteLine("--- License Numbers ---"); foreach (Vechicle v in vs) if (v is ILicenseNo) Console.WriteLine(v.ToString() + " has license number: " + (v as ILicenseNo).LicenseNo); Test for class type Type cast

Single Hierarky Interface Invalid Cast Exception Console.WriteLine("--- Invalid Cast Exception ---"); // Mk. array of vechicles with license number try { ILicenseNo[] xs = { (ILicenseNo)vs[0], (ILicenseNo)vs[1], (ILicenseNo)vs[2] }; } catch (InvalidCastException e) { Console.WriteLine("Not all vechicles has a license no."); } A Cycle class does not implement ILicenseNo. Example file: SingleHierarkyInterface

Explicit Named Interface Same method name in a class and interface Same method name in two or more interfaces. This require Multiple Interface support. // Interface for vechicles having an extra seats that can // be added, fx a side car on a Bike and a Cycle. public interface ISideCar { int numPersons(); } Return number of persons in side car. The Cycle and Bike class may have a side car. public class Bike : Vechicle, ILicenseNo, ISideCar { … public override int numPersons() { return 2; } // There are room for one child or adult. int ISideCar.numPersons() { return 1; } } numPersons required by abstract Vechicle class numPersons required by the side car interface. Example file: ExplicitlyNamedInterface

Explicit Named Interface A cycle can have two kids in a side car. public class Cycle : Vechicle, ISideCar { public Cycle() : base(2, "cycle") { } public override int numPersons() { return 1; } // There are room for two kids. int ISideCar.numPersons() { return 2; } } Return number of persons in side car.

Explicit Named Interface What version of numPersons is used below. Vechicle[] vs = { new Cycle(), new Bike("RX 34213"), new Car("GC 45221") }; // Print vechicles with num persons – // side cars are not included. foreach (Vechicle v in vs) Console.WriteLine(v.ToString() + " has " + v.numPersons() + " seats."); The Cycle and Bike class may have a side car. The numPersons method from the abstract class Vechicle foreach (Vechicle v in vs) if (v is ISideCar) Console.WriteLine(v.ToString() + " has " + ((v as ISideCar).numPersons() + v.numPersons()) + " seats including side car."); else Console.WriteLine(v.ToString() + " has " + v.numPersons() + " seats and no side car."); We know that v supports the ISideCar interface

Single Inheritance Interface An interface can inherit from another interface public interface ISerialNo { String SerialNo { get; set; } } public interface ILicenseNo : ISerialNo { String LicenseNo { get; set; } } All vechicles containing a serial number – most but not baby cycles. A BabyCycle does not have any serial or license number. A Cycle does have a serial number. If a class has a license number, then there will also be a serial number. public class BabyCycle : Vechicle { … } public class Cycle : Vechicle, ISerialNo { … } public class Bike : Vechicle, ILicenseNo { … } public class Car : Vechicle, ILicenseNo { … } Vechicles with a license number must also have a serial number Example file: SingleInheritanceInterface

Single Inheritance Interface Class Diagram having Single Inheritance

Single Inheritance Interface Find all objects that support ISerialNo. foreach (Vechicle v in vs) if (v is ISerialNo) Console.WriteLine(v.ToString() + " has serial number: " + (v as ISerialNo).SerialNo); A type that supports ILicenseNo will also support ISerialNo. Find all objects that support ILicenseNo. They will also support ISerialNo. foreach (Vechicle v in vs) if (v is ILicenseNo) Console.WriteLine(v.ToString() + " has serial number: " + (v as ILicenseNo).SerialNo + " and license number: " + (v as ILicenseNo).LicenseNo); A type that supports ILisenceNo does include the property SerialNo.

Multiple Inheritance Interface An interface can extend other interfaces. public interface ISerialNo { String SerialNo { get; set; } } public interface ILicenseNo : ISerialNo { String LicenseNo { get; set; } } public interface IVechicleName { String Name { get; set; } } public interface IVechiclesMetaData : ILicenseNo, IVechicleName{ int VechicleId { get; } String ppMetaData(); } We give a vechicle a name, eg brand. The Meta Data interface extends two other interfaces. There are no name splashes, but that will often be the case. Then use explicit naming. Example file: MultipleInheritanceInterface

Multiple Inheritance Interface Class Diagram having Multiple Inheritance

Multiple Inheritance Interface Find all objects that support IVedhicleMetaData and print the meta data. Console.WriteLine("--- Meta Data ---"); foreach (Vechicle v in vs) if (v is IVechiclesMetaData) Console.WriteLine( (v as IVechiclesMetaData).ppMetaData()); public class Bike : Vechicle, IVechiclesMetaData { … public String ppMetaData() { return "Meta data for " + this.name + " of type " + this.vechicleName + NewLine + " Serial number: " + this.serialNo + NewLine + " License number: " + this.licenseNo + NewLine + " Vechicle id: " + this.vechicleId + NewLine; }

Some Built In Interfaces A few interface examples: –IEnumerable : An interface containing the method GetEnumerator. GetEnumerator returns an object implementing the interface IEnumerator –IEnumerator : An interface containing methods necessary for the foreach construct, that is, Current, MoveNext and Reset. –ICloneable : An interface containing a Clone method. There are no rules regarding deep and shallow implementations. –IComparable : An interface containing a Compare method to compare the actual object. –IComparer : An interface containing a CompareTo method to compare two objects.

Some Built In Interfaces

IEnumerable and IEnumerator A simple approach is to the a built in enumerator, in this case, in ArrayList. VechicleContainer vContainer = new VechicleContainer(); vContainer.addVechicle(new Cycle()); vContainer.addVechicle(new Bike("RX 34213")); vContainer.addVechicle(new Car("GC 45221")); Console.WriteLine("--- Listing Forwards ---"); foreach (Vechicle v in vContainer) Console.WriteLine(v.ToString()); public class VechicleContainer : IEnumerable { ArrayList vs; public VechicleContainer() { this.vs = new ArrayList(); } public void addVechicle(Vechicle v) { vs.Add(v); } public IEnumerator GetEnumerator() { return vs.GetEnumerator(); } Built in enumerator

IEnumerable and IEnumerator We can also make our own enumerator use yield. Console.WriteLine("--- Listing Backwards ---"); foreach (Vechicle v in vContainer.GetEnumeratorBackwards()) Console.WriteLine(v.ToString()); public class VechicleContainer : IEnumerable { ArrayList vs; public VechicleContainer() { this.vs = new ArrayList(); } public void addVechicle(Vechicle v) { vs.Add(v); } // A Named Iterator public IEnumerable GetEnumeratorBackwards() { for (int i=vs.Count-1; i>=0; i--) yield return vs[i]; } The keyword yield makes the compiled code remember the code location each time an element is returned. Computation starts at that location when returning the next element. The compiler will implicitly generate a class containing the GenEnumerator method.

IEnumerable and IEnumerator You can also code the enumerator your self. public interface MyOwnGetEnumerator { IEnumerator GetEnumerator(); } public class VechicleContainer : IEnumerable, IEnumerator, MyOwnGetEnumerator { … public void Reset() {Console.WriteLine("Reset.");this.i=-1;} public bool MoveNext(){Console.WriteLine("MoveNext"); i++; if (i < vs.Count) return true; else return false; } public object Current {get {Console.WriteLine("Current"); return this.vs[i];}} IEnumerator MyOwnGetEnumerator.GetEnumerator() { return (IEnumerator)this; } } Console.WriteLine("--- Listing with My Own Enumerator ---"); foreach (Vechicle v in (MyOwnGetEnumerator)vContainer) Console.WriteLine(v.ToString());

Collections Classes of System.Collection : ArrayList : Dynamically sized Array Hashtable : Collection of objects identified by a numeric key. Queue : Standard FIFO queue SortedList : Sorted list of key value pairs. Stack : Standard LIFO queue. You should know your collections because they do save you time when used properly. There are many collections to choose from. You can build your own collections by implementing various interfaces. However – We want Generics because we then can build Collections that are more type safe. Collections that provide better performance – less boxing and unboxing. Collections that are polymorphic in the elements they contain The Framework contains a bunch of prefabricated Generics.

Generics Classes of System.Collections.Generic : Dictionary : Generic collection of name / value pairs. List : Resizable list of items. Queue : Standard FIFO queue SortedDictionary : Sorted list of name / value pairs. Stack : Standard LIFO queue.

Generics Example: Build a NameListMap that maps string values to a list of arbitrary typed values T. // Int list NameListMap intMap = new NameListMap (); intMap.insert("A", 1); intMap.insert("A", 2); intMap.insert("B", 3); intMap.insert("B", 4); Console.WriteLine(intMap.pp()); // String list NameListMap stringMap = new NameListMap (); stringMap.insert("A", "Hans"); stringMap.insert("B", "Grethe"); stringMap.insert("A", "Peter"); stringMap.insert("B", "Kurt"); Console.WriteLine(stringMap.pp()); { (A  [1,2]), (B  [3,4])} { (A  [Hans,Peter]), (B  [Grethe,Kurt])} Example: NameListMap

Generics Example: Define the NameListMap class and implement the map using a Dictionary. internal class NameListMap { private Dictionary > map; internal NameListMap() { map = new Dictionary >(); } … } The type of elements in the list. Create the dictionary internal bool exists(String name) { return map.ContainsKey(name); } It is easy to check if a name is already in the map.

Generics Example: When inserting, we have to check if a key (name) already exists and add the value element to the list. If not a new list is created. internal void insert(String name, T t) { List ls; if (map.TryGetValue(name, out ls)) { ls.Add(t); map.Remove(name); map.Add(name, ls); } else { ls = new List (); ls.Add(t); map.Add(name, ls); } Value name exists in the map. Value name does not exists and a new list is created.

Generics Example: Lookup will return the entire list of values for the given name. internal List lookup(String name) { List elem = default(List ); map.TryGetValue(name, out elem); return elem; } Use default to initiate an ”empty” element.

Delegate and Lambda Type safe function pointer Must be fully applied Annonymous methods can be declared on the fly They inherit scope where they are declared. A lambda is mostly syntactic sugar for anonymous delegates Lambda: ( ) => { } Type check (int i, String s) and Type inference (i, s). Short notation for one-liners

Delegate Example List l1 = new List (new int[] { 1, 2, 3, 4 }); printIntList("Before increment:", l1); public static void printIntList(String msg, List map) { List xs = new List (); foreach (int x in map) xs.Add(x.ToString()); Console.WriteLine( msg + " [" + String.Join(",", xs.ToArray()) + "]"); } This is really a stupid example, sorry We define a delegate type and a simple delegate public delegate RT FuncRT (T0 a0); public static FuncRT incByOne = delegate(int x) { return x + 1; };

Delegate Example public static List intListMap(List map,FuncRT fn) { List map2 = new List (); foreach (int x in map) map2.Add(fn(x)); return map2; } We make a simple method, that can apply a delegate of type FuncRT on a list of integers. Use the intListMap method on the incOne delegate List l2 = intListMap(l1, incByOne); printIntList("After increment by 1:", l2); // Add all elements by one - anonymous delegate List l4 = intListMap(l1,delegate (int x) {return x+1;}); printIntList("After increment by 1 (anon):", l4);

Delegate Example // Generate delegate that increments by X public static FuncRT genIncByX(int x) { return delegate(int y) { return y + x; }; } A method can also return a delegate. The parameter x is in scope of the delegate. Generate a delegate that increments with 5. List l3 = intListMap(l1, genIncByX(5)); printIntList("After increment by 5:", l3); Add elements by one with anonymous delegate. List l4 = intListMap(l1,delegate (int x) {return x+1;}); printIntList("After increment by 1 (anon):", l4);

Lambda Example List l5 = intListMap(l1, (int x) => { return x + 1; }); printIntList("After increment by 1 (anon, lambda 1):", l5); The same examples using lambdas. The lambda can access variables in scope. int v = 42; // v is in scope. List l6 = intListMap(l1, x => x + v); printIntList("After increment by 1 (anon, lambda v=42):", l6); Using a named lambda public static FuncRT incByTwo = x => x + 2; List l7 = intListMap(l1, incByTwo); printIntList("After increment by 2 (named lambda):", l7);

Test Data You can use the access implementation of the Hotel Reception system. –Table tblGuest contains 83 guests with real names –Given real guest names you can calculate test data by some stochastic rules. For instance, you want 80% occupied rooms in January, 40% in February etc. –If you calculate ahead you should be able to have some interesting test cases, eg., the search agent should also search in periods where all rooms are occupied. –You can also calculate services received etc. –You should parameterize your program to generate hotels of different occupation.

Stubs A Web service stub is basically an “empty” implementation of the service that fulfills the web service signature. You can make stubs static so that they always return the same value or dynamic so that they return what seems to be different values. If you make it dynamic, then try to have it return values that are good test cases.

Assignments 1.Make the Vechicle class implement ICloneable using deep cloning. Use example SingleHeirarkyInterface. 2.Make the Vechicle class implement ICompareable comparing on the field vechicleName. Use example SingleHeirarkyInterface. 3.Implement a Ping service on hotel.itu.dk 4.Define a BinaryOp delegate type that operates on two integer values, eg plus, minus, multiplication and returns an integer. Make a method applyOp that takes two integer arguments and a BinaryOp delegate type and applies the delegate on the two parameters. Mail your solutions to

Group Meetings Friday February 13 1.We all meet at (I go by train  ) 2.Group 1: – Group 2: – Group 3: – Group 4: – Group 5: – Group 6: – 11.30