Generics Programming in C# Generics CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis.

Slides:



Advertisements
Similar presentations
Sml2java a source to source translator Justin Koser, Haakon Larsen, Jeffrey Vaughan PLI 2003 DP-COOL.
Advertisements

Final and Abstract Classes
Optional Static Typing Guido van Rossum (with Paul Prescod, Greg Stein, and the types-SIG)
Object Oriented Programming with Java
Object-Oriented Programming Python. OO Paradigm - Review Three Characteristics of OO Languages –Inheritance It isn’t necessary to build every class from.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 17 Templates.
INTERFACES IN JAVA 1.Java Does not support Multiple Inheritance directly. Multiple inheritance can be achieved in java by the use of interfaces. 2.We need.
Static Members, Structures, Enumerations, Generic Classes, Namespaces Learning & Development Team Telerik Software Academy.
Copyright © 2012 Pearson Education, Inc. Chapter 9 Delegates and Events.
Generic programming in Java
Equality Programming in C# Equality CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis.
ITEC200 – Week03 Inheritance and Class Hierarchies.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
IEG3080 Tutorial 7 Prepared by Ryan.
CPSC150 Abstract Classes and Interfaces Chapter 10.
Class template Describing a generic class Instantiating classes that are type- specific version of this generic class Also are called parameterized types.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
C# Programming: From Problem Analysis to Program Design1 Advanced Object-Oriented Programming Features C# Programming: From Problem Analysis to Program.
Generic Programming David Rabinowitz. June 14, 2006 Object Oriented Design Course 2 The problem Assume we have a nice Stack implementation. Our stack.
Lecture 9 Concepts of Programming Languages
 2006 Pearson Education, Inc. All rights reserved Generics.
OOP in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
CSE 332: C++ templates and generic programming I Motivation for Generic Programming in C++ We’ve looked at procedural programming –Reuse of code by packaging.
Templates CS212 & CS-240. Reuse Templates allow extending our classes Allows the user to supply certain attributes at compile time. Attributes specified.
BASE CLASSES AND INHERITANCE CHAPTER 4. Engineer Class.
Computer Science and Engineering College of Engineering The Ohio State University Interfaces The credit for these slides goes to Professor Paul Sivilotti.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 11 th Lecture Pavel Ježek
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
Tuc Goodwin  Object and Component-Oriented Programming  Classes in C#  Scope and Accessibility  Methods and Properties  Nested.
Session 08 Module 14: Generics and Iterator Module 15: Anonymous & partial class & Nullable type.
Hoang Anh Viet Hà Nội University of Technology Chapter 1. Introduction to C# Programming.
The Factory Patterns SE-2811 Dr. Mark L. Hornick 1.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
1 Generics Chapter 21 Liang, Introduction to Java Programming.
C# Programming: From Problem Analysis to Program Design1 10 Advanced Object-Oriented Programming Features C# Programming: From Problem Analysis to Program.
[ISRAR ALI] Hammad Khan. The namespace keyword is used to declare a scope. Making software components reusable can result in naming collisions (two classes.
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.
1 Abstract Classes and Interfaces. 2 The abstract Modifier  The abstract class –Cannot be instantiated –Should be extended and implemented in subclasses.
ISBN Chapter 11 Abstract Data Types and Encapsulation Concepts.
Overview of C++ Templates
1 CSE 331 Generics (Parametric Polymorphism) slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
PROGRAMMING IN C#. Collection Classes (C# Programming Guide) The.NET Framework provides specialized classes for data storage and retrieval. These classes.
ITF11006.NET Generics. Generics - Sample Recent Generics - Characteristics Performance Type Safety Binary Code Reuse Code Bloat Naming Guidelines.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics C# Language &.NET Platform 11 th Lecture Pavel Ježek
Introduction to Object-Oriented Programming Lesson 2.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
This In Java, the keyword this allows an object to refer to itself. Or, in other words, this refers to the current object – the object whose method or.
ENEE150 – 0102 ANDREW GOFFIN Abstract Data Types.
Lecture 5:Interfaces and Abstract Classes Michael Hsu CSULA.
Lecture 6:Interfaces and Abstract Classes Michael Hsu CSULA.
Static data members Constructors and Destructors
2.7 Inheritance Types of inheritance
Module 5: Common Type System
Jim Fawcett CSE681 – Software Modeling and Analysis Fall 2005
Generics, Lambdas, Reflections
Lecture 9 Concepts of Programming Languages
Chapter 19 Generics Dr. Clincy - Lecture.
CISC124 Assignment 4 on Inheritance due next Monday, the 12th at 7pm.
Conditional Statements
Interfaces.
Lecture 16 - Interfaces Professor Adams.
Generic programming in Java
Generics, Lambdas, Reflections
Abstract Classes and Interfaces
Chapter 14 Abstract Classes and Interfaces
CMPE212 – Reminders Assignment 4 on Inheritance due next Friday.
Generics, Lambdas and Reflection
Lecture 9 Concepts of Programming Languages
Presentation transcript:

Generics Programming in C# Generics CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis

Motivation See the Type Unification and the use of the ArrayList set of slides. In summary, four main goals: 1. Increase type safety (statically) 2. Eliminate type casts 3. Eliminate boxing and unboxing 4. C++ has templates Syntax is similar to C++

Generic Syntax Write public class Stack { … } T is the type variable Stack myStack = new Stack (); Can have several type parameters Dictionary Compiler will now enforce type safety myStack.Push(4.3) // Compiler error Design Note It is customary to use T for a generic single type. For multiple types or in cases where the type is clear a more specific name should be used. This is pre-fixed by a capital T.

Terminology Why the name Generic? We separate the behavior from the type allowing more generic behavior descriptions. Also called Parametric Polymorphism We supply a type parameter and the same code or behavior applies to this type.

Generic Parameterization Generics can be used with: Types Struct Interface Class Delegate Methods

Using Generics - Types Can be used to easily create non-generic derived types: public class IntStack : Stack { }

Using Generics - Types Can be used in internal fields, properties and methods of a class: public struct Customer { private static List customerList; private T customerInfo; public T CustomerInfo { get; set; } public int CompareCustomers( T customerInfo ); } A better type name here would be TCustomerInfo

Using Generics - Types Using the type is like using any other non-generic type. The type parameter only needs to be specified during instantiation. Customer fred = new Customer (); fred.CustomerInfo = 4;

Verifying Generic Types In C#, generic types can be compiled into a class library or dll and used by many applications. Differs from C++ templates, which use the source code to create a new type at compile time. Hence, when compiling a generic type, the compiler needs to ensure that the code will work for any type.

Generic Constraints What if we want to write public class Stack public T PopEmpty() { return new T(); } } Why would the compiler produce an error for this? What if my type requires parameters on all of their constructors?

Generic Constraints A new keyword, where provides constraints on a type parameter. A base class or interface can be used as a constraint. For instance public interface IDrawable { public void Draw(); } Need a constraint that our type T implements the IDrawable interface. public class SceneGraph where T : IDrawable { public void Render() { … T node; … node.Draw(); } } No need to cast Compiler uses type information to decide Again, this can be enforced at compile time

Generic Constraints Can also specify a class constraint. That is, require a reference type: public class CarFactory where T : class { private T currentCar = null; Forbids CarFactory and other value types. Useful since I can not set an int to null.

Generic Constraints Alternatively, require a value (struct) type. public struct Nullable where T : struct { private T value; Fixes the new problem (but is limited): public class Stack where T : struct { public T PopEmpty() { return new T(); } }

Using a Default Value You may need to initialize a variable public class GraphNode { private T nodeLabel; private void ClearLabel() { nodeLabel = null; } Why doesnt this work? What do I do if T is int?

Using a Default Value The default keyword public class GraphNode { private T nodeLabel; private void ClearLabel() { nodeLabel = default(T); } If T is a reference type default(T) will be null. For value types all bits are set to zero.

Constructor Constraint Special constraint using the new keyword: public class Stack where T : new() { public T PopEmpty() { return new T(); } } Parameter-less constructor constraint Type T must provide a public parameter-less constructor No support for other constructors or other method syntaxes. The new() constraint must be the last constraint.

Primary Constraints A generic type parameter, like a regular type, can have zero or one primary constraints, including: Derived from a non-sealed concrete or abstract base type The class constraint The struct constraint

Secondary Constraints A generic type parameter, like a regular type, can have zero or more interface constraints public class GraphNode { where T : ICloneable, IComparable … }

The where clause A type parameter can only have one where clause, so all constraints must be specified within a single where clause. Not allowed: public class GraphNode { where T : MyNode, ICloneable where T : IComparable, new() … }

Multiple Type Parameters A generic type can be parameterized with many type place-holders; public interface IFunction { TRange Evaluate(TDomain sample); } 2D, 3D, complex function support with mappings from one domain to another.

Dependent Constraints Each type parameter can have its own set of constraints (and own where class). You can also have one type parameter be dependent on another. public class SubSet where U : V public class Group where V : IEnumerable { … }

Compilation Errors class A {...} class B {...} class Incompat where S: A, T where T: B {... }

Compilation Errors class StructWithClass where S: struct, T where T: U where U: A {... }

Compilation Errors interface I { void F(); } class X : I, I { void I.F() {...} void I.F() {...} }

Generic Methods C# also allow you to parameterize a method with generic types: public static void Swap ( ref T a, ref T b ) { T temp = a; a = b; b = temp; }

Generic Methods The method does not need to be static. public class Report : where T IFormatter { } public class Insurance { public Report ProduceReport () where T : IFormatter { … }

Type Covariance We say a type Derived is Covariant to the type, Base, if Derived can be cast to Base. Generic types are not covariant. MyClass md; MyClass mb = md;

Java Generics v. C# Java made the decision to keep backward compatible bytecode. Hence old JVMs can run the new Java with generics code. Ruins run-time type reflection. C# 2.0 requires a new CLR. Generics are supported in the IL code.

C++ Templates v. C# C++ has slightly more powerful parametric polymorphism in that non- type parameters can also be used. No run-time type support or reflection. Run-time (generics) versus compile-time (templates) Requires you to expose your source code to everyone.

Assignment In addition to Reading Chapters 1-3 of the textbook and going through these lectures, you should: Memorize the C# keywords a-I in the appendix of the book. Think of how you would design a program or set of programs to display memorization questions or flashcards. Read careful through the errata for book for Chapters 1-4.