Lecture 6: Generics. Lisa (Ling) Liu

Similar documents
Generics. Thomas J. Fuchs

C# Generics. Object Oriented Programming (236703) Winter

CS313D: ADVANCED PROGRAMMING LANGUAGE

02 Features of C#, Part 1. Jerry Nixon Microsoft Developer Evangelist Daren May President & Co-founder, Crank211

Introduction to Programming Using Java (98-388)

INF 212 ANALYSIS OF PROG. LANGS Type Systems. Instructors: Crista Lopes Copyright Instructors.

INF 212/CS 253 Type Systems. Instructors: Harry Xu Crista Lopes

Java Design Goals. Lecture 32: Java. Java Original implementations slow! Exceptions & Subtyping. - void method readfiles() throws IOException {...}!

What is Inheritance?

9 A Preview of.net 2.0

INDEX. A SIMPLE JAVA PROGRAM Class Declaration The Main Line. The Line Contains Three Keywords The Output Line

Chair of Software Engineering. Java and C# in Depth. Prof. Dr. Bertrand Meyer. Exercise Session 7. Nadia Polikarpova

Application Architecture Using Generics C#.Net 2.0

Lecture 13: Subtyping

Java 5. Lecture 33: Java 5. Generics Finally Added. Constrained Genericity

T, Earl Grey, Hot: Generics in.net

Lecture Overview. [Scott, chapter 7] [Sebesta, chapter 6]

Java Fundamentals (II)

Exercise 8 Parametric polymorphism November 18, 2016

Static program checking and verification

COPYRIGHTED MATERIAL. Contents. Part I: C# Fundamentals 1. Chapter 1: The.NET Framework 3. Chapter 2: Getting Started with Visual Studio

Introduce C# as Object Oriented programming language. Explain, tokens,

generic programming alberto ferrari university of parma

Object typing and subtypes

Exercise 8 Parametric polymorphism November 17, 2017

Hierarchical inheritance: Contains one base class and multiple derived classes of the same base class.

Object-Oriented Languages and Object-Oriented Design. Ghezzi&Jazayeri: OO Languages 1

C#: framework overview and in-the-small features

Object-Oriented Programming. Lecture 2 Dr Piotr Cybula

Subtyping (cont) Formalization of Subtyping. Lecture 15 CS 565. Inversion of the subtype relation:

Distributed Systems Recitation 1. Tamim Jabban

C++ Important Questions with Answers

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

CSE 431S Type Checking. Washington University Spring 2013

Object-Oriented Programming

Rules and syntax for inheritance. The boring stuff

Chair of Software Engineering. Languages in Depth Series: Java Programming. Prof. Dr. Bertrand Meyer. Exercise Session 10

Template. SSE2034: System Software Experiment 3, Fall 2018, Jinkyu Jeong

C++ Inheritance and Encapsulation

CSE 331 Software Design and Implementation. Lecture 13 Generics 1

Multiple Choice: 2 pts each CS-3020 Exam #3 (CH16-CH21) FORM: EX03:P

Instantiation of Template class

Subtyping (cont) Lecture 15 CS 565 4/3/08

Previous C# Releases. C# 3.0 Language Features. C# 3.0 Features. C# 3.0 Orcas. Local Variables. Language Integrated Query 3/23/2007

Programming Kotlin. Familiarize yourself with all of Kotlin s features with this in-depth guide. Stephen Samuel Stefan Bocutiu BIRMINGHAM - MUMBAI

Topics Covered Thus Far. CMSC 330: Organization of Programming Languages. Language Features Covered Thus Far. Programming Languages Revisited

Discussion. Type 08/12/2016. Language and Type. Type Checking Subtypes Type and Polymorphism Inheritance and Polymorphism

Software Development (cs2500)

Java and C# in Depth

Java Inheritance. Written by John Bell for CS 342, Spring Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources.

CSE 331 Software Design and Implementation. Lecture 14 Generics 2

Module - 3 Classes, Inheritance, Exceptions, Packages and Interfaces. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

CMSC 330: Organization of Programming Languages

CSE 331 Software Design and Implementation. Lecture 14 Generics 2

TEMPLATE IN C++ Function Templates

Chapter 5 Object-Oriented Programming

Java: introduction to object-oriented features

Compilation 2009 Java 1.5 Features. Jan Midtgaard Michael I. Schwartzbach Aarhus University

Microsoft. Microsoft Visual C# Step by Step. John Sharp

Lecture 13: Introduction to inheritance and genericity

Classes. Logical method to organise data and functions in a same structure. Also known as abstract data type (ADT).

Operators and Expressions

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

Short Notes of CS201

Object-Oriented Software Construction

How to be a C# ninja in 10 easy steps. Benjamin Day

Lecture 14: More Inheritance & Genericity

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

CS201 - Introduction to Programming Glossary By

Topics Covered Thus Far CMSC 330: Organization of Programming Languages

Collections Algorithms

Data Types. Every program uses data, either explicitly or implicitly to arrive at a result.

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

Generics with Type Bounds

Agenda CS121/IS223. Reminder. Object Declaration, Creation, Assignment. What is Going On? Variables in Java

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

CSE 331 Summer 2017 Final Exam. The exam is closed book and closed electronics. One page of notes is allowed.

Lecture 13 & 14. Single Dimensional Arrays. Dr. Martin O Connor CA166

INSTRUCTIONS TO CANDIDATES

Type Hierarchy. Lecture 6: OOP, autumn 2003

301AA - Advanced Programming [AP-2017]

C# Adds Useful Features

Lecture Outline. Parametric Polymorphism and Java Generics. Polymorphism. Polymorphism

Microsoft Visual C# Step by Step. John Sharp

Overriding המחלקה למדעי המחשב עזאם מרעי אוניברסיטת בן-גוריון

Introduction to C++ Introduction to C++ Dr Alex Martin 2013 Slide 1

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Oops known as object-oriented programming language system is the main feature of C# which further support the major features of oops including:

Pierce Ch. 3, 8, 11, 15. Type Systems

CS121/IS223. Object Reference Variables. Dr Olly Gotel

C#.Net. Course Contents. Course contents VT BizTalk. No exam, but laborations

Function Overloading

Refactoring Java Generics by Inferring Wildcards, In Practice

Universe Type System for Eiffel. Annetta Schaad

C++ Coding Standards. 101 Rules, Guidelines, and Best Practices. Herb Sutter Andrei Alexandrescu. Boston. 'Y.'YAddison-Wesley

Where do we stand on inheritance?

Official Survey. Cunning Plan: Focus On Objects. The Need for a Calculus. Object Calculi Summary. Why Not Use λ-calculus for OO?

Advanced Object-Oriented Programming. 11 Features. C# Programming: From Problem Analysis to Program Design. 4th Edition

Polymorphism Part 1 1

Advanced C++ Topics. Alexander Warg, 2017

Transcription:

Chair of Software Engineering C# Programming in Depth Prof. Dr. Bertrand Meyer March 2007 May 2007 Lecture 6: Generics Lisa (Ling) Liu

Overview Problems with untyped collections Generics Define generics Covariance C# programming lecture 6: Generics 2

The problems with untyped collections ArrayList list = new ArrayList(); double a; list.add(2); a = (double)list[0]; Problems: Performence Type safety.locals init ([0] class [mscorlib]system.collections.arraylist list, [1] float64 a) newobj instance void [mscorlib]system.collections.arraylist::.ctor() box [mscorlib]system.int32 callvirt instance int32 [mscorlib]system.collections.arraylist::add(object) callvirt instance object [mscorlib]system.collections.arraylist::get_item(int32) unbox.any [mscorlib]system.double C# programming lecture 6: Generics 3

Generics Introduce the concept of type parameter Defer the specification of types until declaration or instantiation Avoid the cost of runtime boxing operation and type casts Avoid the risk of runtime casts Allow you to define a type-safe data structure or a utility helper class without committing to the actual data types used. C# programming lecture 6: Generics 4

Generic namespace Strongly typed collections Compare <T> Dictionary <K, T> SortedDictionary <K, T> List <T> Queue <T> Stack <T> C# programming lecture 6: Generics 5

List<int> l = new List<int>(); double a; l.add(2); a = list[0]; No boxing and unboxing The compiler checks the type compatibility, if necessary, does implicit type conversion, otherwise reports errors

Define generic methods access_mofifier return_type method_name <T> (arguments) public static void Swap<T> (ref T a, ref T b) T temp; temp = a; a = b; b = temp; static void Main (string[] args) int x, y; x = 0; y = 1; GenericClass.Swap(ref x, ref y); C# programming lecture 6: Generics 7

Define generic classes access_mofifier class_name <T> : inheritance list public class Point<T> private T xpos; private T ypos; public Point (T xval, T yval) C# programming lecture 6: Generics 8

default keyword in generic code In generic code, default keyword is used to set a type parameter to its default value Numeric values have a default value of 0 Reference types have a default value of null C# programming lecture 6: Generics 9

Creating a custom generic collection access_mofifier class_name <T> : IEnumerable <T> IEnumerable<> extends the nongeneric IEnumerable interface The class that implements interface IEnumerable<T> should implement two versions of the GetEnumerator() method C# programming lecture 6: Generics 10

public interface IPerson string Name get; public class Person : IPerson private string _name; public Person() public string Name get return this._name; set this._name = value; public static class PersonFactory public static List<IPerson> CreatePeople() List<Person> people = new List<Person>(); return people; pass compilation?

Car[] arrcar = new Car[10]; SportsCar[] arrsportscar = new SportsCar[10]; arrcar = arrsportscar; compiler error List<Car> lcar = new List<Car>(); List<SportsCar> lsportscar = new List<SportsCar>(); lcar = lsportscar; CarList<Car> colcar = new CarList<Car>(); CarList<SportsCar> colsportscar = new CarList<SportsCar>(); colcar = colsportscar; compiler error

Covariance & Contravariance substitution principle: any expression of type t can be substituted by an expression of type s if s t (Here, denotes the subtype relationship) A covariant type operator in a type system preserves the ordering of types A contravariant type operator in a type system reverses the ordering of types C# programming lecture 6: Generics 13

Subtyping relation for functional types Contravariant rule (Cardelli [1998]): if T 1 S 1 and S 2 T 2 then S 1 -> S 2 T 1 -> T 2 It sounds kind of counterintuitive It reflects the famous advice about the implementation protocols: be liberal in what you accept, and conservative in what you send. It achieves the static type safety C# programming lecture 6: Generics 14

C# covariance Array of reference-types are covariant object[] b = new string[1]; Array of value-types are invariant int[] is not a subtype of double[] Delegates are covariant Method overriding is not covariant C# programming lecture 6: Generics 15

public delegate CarDelegate(); public static Car GetBasicCar() return new Car(); public static SportsCar GetSportsCar() return new SportsCar(); static void Main() CarDelegate targeta = new CarDelegate(GetBasicCar); Car c = targeta(); CarDelegate targetb = new CarDelegate(GetSportCar); SportsCar sc = (SportsCar) targetb();

class CarList<T>: IEnumerable<T> private List<T> arcars = new List<T>(); public void PrintPetName(int pos) Console.WriteLine(arCars[pos].Name); pass compilation?

Type parameter constraints Unbound generic when a type parameter is not constrained in any way, the generic type is said to be unbound Bound generic use the keyword where to set the constraints of a generic type. the constraint list is placed after the generic type s base class and interface list. C# programming lecture 6: Generics 18

Possible constraints for generic parameters where T: struct where T: class where T: new () where T: NameOfBaseClass where T: NameOfInterface C# programming lecture 6: Generics 19

Examples public class MyGenericClass<T> where T: new() public class MyGenericClass<T> where T: class, IDrawable, new() public class MyGenericClass<T> : MyBase, ISomeInterface where T: struct public class MyGenericClass<K, T> where K: new() where T: IComparable<T> C# programming lecture 6: Generics 20

Inherit generic class Generic class can be the base class to other classes If a nongeneric class inherits a generic class, the derived class must specify a type parameter If the derived type is generic as well, the child class can (optionally) reuse the type placeholder Any constraints placed on the base class must be honored by the derived type C# programming lecture 6: Generics 21

public class MyList<T> public class MyStringList: MyList<string> public class MyList<T> where T: new() public class MySubList<T> : MyList<T> where T: new()

Creating generic interface public interface IBinaryOperations<T> T Add(T arg1, T arg2); T Subtract(T arg1, T arg2); C# programming lecture 6: Generics 23

Creating generic delegates public delegate void MyGenericDelegate<T> (T arg) MyGenericDelegate<string> strtarget = new MyGenericDelegate<string> (StringTarget); C# programming lecture 6: Generics 24

Questions C# programming lecture 6: Generics 25