Generics. Thomas J. Fuchs

Similar documents
Lecture 6: Generics. Lisa (Ling) Liu

9 A Preview of.net 2.0

C# Generics. Object Oriented Programming (236703) Winter

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

COEN244: Class & function templates

C # Version 2.0 Specification

Object-Oriented Programming

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

What property of a C# array indicates its allocated size? What keyword in the base class allows a method to be polymorphic?

Experience with Generic C#

Cpt S 122 Data Structures. Course Review Midterm Exam # 2

Learning C# 3.0. Jesse Liberty and Brian MacDonald O'REILLY. Beijing Cambridge Farnham Köln Sebastopol Taipei Tokyo

Introduction to Programming Using Java (98-388)

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

C++ Important Questions with Answers

Programming C# 5.0. Ian Griffiths O'REILLY' Beijing Cambridge * Farnham Kbln Sebastopol Tokyo

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

Visual C# 2012 How to Program by Pe ars on Ed uc ati on, Inc. All Ri ght s Re ser ve d.

Collections. Enumeration.

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

CSE 431S Type Checking. Washington University Spring 2013

Object Oriented Programming. Solved MCQs - Part 2

Chapter 14. Collections

C# s A Doddle. Steve Love. ACCU April 2013

Parametric polymorphism and Generics

C++ (Non for C Programmer) (BT307) 40 Hours

Exercise 8 Parametric polymorphism November 17, 2017

Exercise 8 Parametric polymorphism November 18, 2016

And Even More and More C++ Fundamentals of Computer Science

Building non-windows applications (programs that only output to the command line and contain no GUI components).

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

Cpt S 122 Data Structures. Templatized Stack

The list abstract data type defined a number of operations that all list-like objects ought to implement:

Topic 9: Type Checking

Topic 9: Type Checking

CE204 Data Structures and Algorithms Part 2

Today. andyoucanalsoconsultchapters6amd7inthetextbook. cis15-fall2007-parsons-lectvii.1 2

Polymorphic (Generic) Programming in Java

10/17/2011. Object Oriented Software Development. Types of interface. Interfaces example

PARAMETRIC POLYMORPHISM

Instantiation of Template class

Applied object oriented programming. 4 th lecture

Comp151. Function Templates & Class Templates

Introducing Generics

Cpt S 122 Data Structures. Course Review FINAL. Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University

Whidbey Enhancements to C# Jeff Vaughan MSBuild Team July 21, 2004

Increases Program Structure which results in greater reliability. Polymorphism

LINQ Language-Integrated Query Introduction

Introduction to C++ Introduction. Structure of a C++ Program. Structure of a C++ Program. C++ widely-used general-purpose programming language

Chapter 15: How to Work with Interfaces and Generics

(12-1) OOP: Polymorphism in C++ D & D Chapter 12. Instructor - Andrew S. O Fallon CptS 122 (April 3, 2019) Washington State University

Object-Oriented Programming in C# (VS 2015)

Introduction to C++ with content from

C# Adds Useful Features

Chapter 14 Abstract Classes and Interfaces

VIRTUAL FUNCTIONS Chapter 10

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

Computing is about Data Processing (or "number crunching") Object Oriented Programming is about Cooperating Objects

Ken Casada Developer Evangelist Microsoft Switzerland.

Parametric Polymorphism for Java: A Reflective Approach

C# Programming in the.net Framework

Chapter 1: Object-Oriented Programming Using C++

CSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community

CSCI 3155: Principles of Programming Languages Exercise sheet #14 28 June 2007

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

Object Declaration. <class name>: the name of the class to which the object belongs <object name>: the name of the object (any valid identifier)

EL2310 Scientific Programming

Microsoft Visual C# Step by Step. John Sharp

Short Notes of CS201

Java classes cannot extend multiple superclasses (unlike Python) but classes can implement multiple interfaces.

Course Hours

CS201 - Introduction to Programming Glossary By

Chapter 1 Getting Started

Object-Oriented Programming

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

Lecture 10 OOP and VB.Net

Object Oriented Programming

C# MOCK TEST C# MOCK TEST I

Framework Fundamentals

Course Text. Course Description. Course Objectives. StraighterLine Introduction to Programming in C++

Chapter 5 Object-Oriented Programming

CSE 331 Software Design and Implementation. Lecture 13 Generics 1

.Net Technologies. Components of.net Framework

Computer Programming, I. Laboratory Manual. Final Exam Solution

CS-201 Introduction to Programming with Java

Table of Contents Preface Bare Necessities... 17

Java Class Design. Eugeny Berkunsky, Computer Science dept., National University of Shipbuilding

Objectives. Introduce the core C# language features class Main types variables basic input and output operators arrays control constructs comments

More Relationships Between Classes

COMP322 - Introduction to C++

ECE 3574: Dynamic Polymorphism using Inheritance

Generic types. Announcements. Raw ArrayLists. Generic types (cont.) Creating a raw ArrayList: Accessing a raw ArrayList:

Closed book but one sheet, both sides, of A4 paper is allowed. Section 2.5 of the text Generics in the Java Programming Languages by Gilad Bracha

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

Object-Oriented Programming in C# (VS 2012)

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

Compiler Construction 2009/2010 Polymorphic Types and Generics

Lecture Notes on Queues

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

Lab 2 (More Inheritance, Interfaces, Delegates)

Transcription:

Generics Thomas J. Fuchs

Parametric Polymorphism (Generics) Benefits: Code reuse Faster code (no runtime casts) Safer programming (static type-checking) World s first cross-language generics (not just for C#, but C++ and VB and other languages running on the CLR) For use in: Collection classes Algorithms Structured types

Generics Why generics? Type checking, no boxing, no downcasts Increased sharing (typed collections) How are C# generics implemented? Instantiated at run-time, not compile-time Checked at declaration, not instantiation Work for both reference and value types Exact run-time type information

Implementation Details Type-checked at declaration, not at use (unlike C++ templates) After type check, translated to Generic IL bytecode which supports explicit type parameters and validation of generic code

The Most Simple Example List<T> mylist = new List<T>();

The Most Simple Example List<int> mylist = new List<int>();

Placeholders for Generic Types T type K key V value

Generics Collection classes Collection interfaces Collection base classes Utility classes List<T> Dictionary<K,V> SortedDictionary<K,V> Stack<T> (LIFO) Queue<T> (FIFO) IList<T> IDictionary<K,V> ICollection<T> IEnumerable<T> IEnumerator<T> IComparable<T> IComparer<T> Collection<T> KeyedCollection<T> ReadOnlyCollection<T> Reflection Nullable<T> EventHandler<T> Comparer<T>

The default Keyword in Generic Code public void ResetPoint() { xpos = default(t); ypos = default(t); Numerical values have a default value of 0. Reference types have a default value of null. Fields of structures are set accordingly to 0 or null.

Constrain Type Parameters Using where When a type parameter is not constrained in any way, the generic type is said to be unbound. Unbound type parameters are assumed to have only the members of System.Object.

Constraints for Generic Type Parameters where T : struct where T : class where T : new() where T : NameOfBaseClass where T : NameOfInterface

Iterators Methods that incrementally compute and return a sequence of values class Program { static IEnumerable<int> Range(int start, int count) { for (int i = 0; i < count; i++) yield return start + i; static IEnumerable<int> Squares(IEnumerable<int> source) { foreach (int x in source) yield return x * x; static void Main() { foreach (int i in Squares(Range(0, 10))) Console.WriteLine(i); 0 1 4 9 16 25 36 49 64 81

Notes Can implement more than one iterator public IEnumerable<T> BottomToTop { get { for (int i = 0; i < count; i++) { yield return items[i]; public IEnumerable<T> TopToBottom { get { return this;

Additional Functionality Generic Base Classes Can implement virtual or a abstract methods. Generic Interfaces Generic Delegates

Slides partly based on a presentation from: Anders Hejlsberg C# 2.0 and Future Directions

Resources Course Homepage: se.inf.ethz.ch/teaching/ss2007/251-0290-00 Exercise Material: www.inf.ethz.ch/personal/thomas.fuchs

Generics public class List<T> { private T[] elements; private int count; public void Add(T element) { if (count == elements.length) Resize(count * 2); elements[count++] = element; public T this[int index] { get { return elements[index]; set { elements[index] = value; public int Count { get { return count;

Generics List<int> intlist = new List<int>(); intlist.add(1); intlist.add(2); intlist.add("three"); // No boxing // No boxing // Compile-time error int i = intlist[0]; // No cast required

Performance Quicksort on 1,000,000 elements Times in seconds 4 3.5 3 Generic Non-generic (object) 2.5 2 1.5 1 0.5 0 int double string (length) element type Generics for C# and.net MSR Cambridge Copenhagen 13 th May 2003 21

Generics public class List<T> { private T[] object[] elements; elements; private int count; public void Add(T Add(object element) element) { { if (count == elements.length) Resize(count * 2); elements[count++] = element; public Tobject this[int this[int index] index] { { get { return elements[index]; set { elements[index] List<int> = intlist value; intlist = new = List(); new List<int>(); intlist.add(1); // No Argument boxing is boxed public int Count { intlist.add(2); // No Argument boxing is boxed get { return count; intlist.add("three"); // Compile-time Should be an error int i = intlist[0]; (int)intlist[0]; // No cast // required Cast required