11
Generics 1 C# 30 C# 3.0 C# 3.0 Chapter 19 – Generics © Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel Introduction Generics 2 C# 30 Introduction Generic code is ital for creating Generic code is vital for creating collections and common algorithms Often reusability is ignored just because the data type is not the same is not the same Polymorphism can help, but: Often comes with a performance penalty Can’t control existing types that don’t implement an interface or override a virtual method Generics are key to reusable and efficient Generics are key to reusable and efficient code © Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Chapter 19 - Generics

Embed Size (px)

DESCRIPTION

y

Citation preview

Page 1: Chapter 19 - Generics

Generics 1C# 30

C# 3.0C# 3.0

Chapter 19 – Generics

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

IntroductionGenerics 2C# 30

Introduction

Generic code is ital for creating• Generic code is vital for creating collections and common algorithmsg– Often reusability is ignored just because the data type

is not the sameis not the same

• Polymorphism can help, but:– Often comes with a performance penalty

– Can’t control existing types that don’t implement an g yp pinterface or override a virtual method

• Generics are key to reusable and efficient• Generics are key to reusable and efficient code

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Page 2: Chapter 19 - Generics

Motivation: CollectionsGenerics 3C# 30

Motivation: Collections

• Non generic collection:• Non generic collection:ArrayList employees = new ArrayList();

l Add(  E l ("St "  "B ll "))employees.Add(new Employee("Steve", "Ballmer"));// return value must be cast downEmployee employee = (Employee)employees[0];

• Generic collection:

p y p y ( p y ) p y [ ];

Generic collection:List<Employee> employees = new List<Employee>();employees Add(new Employee("Steve"  "Ballmer"));employees.Add(new Employee( Steve ,  Ballmer ));// return value is guaranteed to be EmployeeEmployee employee = employees[0];

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Motivation: CollectionsGenerics 4C# 30

Motivation: Collections

• Non generic collection:• Non generic collection:ArrayList polygon = new ArrayList();

l Add(  P i t(0  0)) //B i !polygon.Add(new Point(0, 0)); //Boxing!Point p = (Point)polygon[0]; //Unboxing!

• Generic collection:Generic collection:List<Point> polygon = new List<Point>();polygon Add(new Point(0  0)); //No boxingpolygon.Add(new Point(0, 0)); //No boxingPoint p = polygon[0]; //No unboxing

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Page 3: Chapter 19 - Generics

Generic TypesGenerics 5C# 30

Generic Types

• Generic types have type parameters• Generic types have type parameters– Placeholders that will be replaced with the data type

specified by client codespecified by client code

public class Matrix<T> {...}bli  i t f  IV t T { }

• Client code:

public interface IVector<T> {...}

Client code:Matrix<int> intMatrix = new Matrix<int>();M t i t i t i M t i    M t i t i ()Matrix<string> stringMatrix = new Matrix<string>();Matrix<Cmd> cmdMatrix = new Matrix<Cmd>();

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Generic ConstraintsGenerics 6C# 30

Generic Constraints

Generic code can’t ass me an thing• Generic code can’t assume anything about the type parameteryp p– Except that it derives from Object

• One alternative is to use is and as cast• One alternative is to use is and as, cast to interfaces / base classes and work with that

This is not compile time safe: Code can break at run– This is not compile-time safe: Code can break at run-time, there is no good contract with the client

A th lt ti i t i t• Another alternative is constraints– Get you compile-time type safety!

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

y p yp y

Page 4: Chapter 19 - Generics

Defining ConstraintsGenerics 7C# 30

Defining Constraints

Constraint Description

where T : struct T must be a value-typeyp

where T : class T must be a reference type

where T : new() T must have a public default ctorwhere T : new() T must have a public, default ctor(appears last)

here T T m st be or deri e from basewhere T : <base>

T must be or derive from base

fwhere T : <interface>

T must be or implement interface. The constraining interface/s can l b ialso be generic

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Constraints CombinedGenerics 8C# 30

Constraints Combined

public class Matrix<T>where T : class, IPrintable<T>, new()

{{public void Print(){

foreach (T[] row in _rows){

foreach (T printable in row)foreach (T printable in row)printable.Print();

Console.WriteLine();}

}}}

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Page 5: Chapter 19 - Generics

Unbounded Type ParameterGenerics 9C# 30

Unbounded Type Parameter

Witho t constraints e are er limited• Without constraints we are very limited:– The != and == operators cannot be used

– They can be converted to and from object or explicitly converted to any interface typey yp

– They can be compared to null but the comparison will always return false if the type argument is a value always return false if the type argument is a value type

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Inheritance IssuesGenerics 10C# 30

Inheritance Issues

• Generic classes can inherit from open• Generic classes can inherit from open generic classes or concrete types:public class Matrix<T> : BaseMatrix {...}public class Matrix<T> : BaseMatrix<int> {...}

Non generic classes can inherit from

public class Matrix<T> : BaseMatrix<T> {...}

• Non-generic classes can inherit from closed generic classes://OKpublic class IntMatrix : Matrix<int> {...}//D ’t  il//Doesn’t compilepublic class MatrixEx : Matrix<T> {...}

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Page 6: Chapter 19 - Generics

InterfacesGenerics 11C# 30

Interfaces

Use generic interfaces to a oid bo ing• Use generic interfaces to avoid boxing and unboxing (value types)public interface IComparable<T> {

int CompareTo(T other);p ( );}

p blic class Matri <T>  here T :

Th i h i l l

public class Matrix<T> where T :IComparable<T>, IEquatable<T> {...}

• The same inheritance rules apply

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Generic MethodsGenerics 12C# 30

Generic Methods

A generic method is a method that is• A generic method is a method that is declared with type parameters.yp ppublic void Sort<T>(T[] array2Sort) {...}public void Swap<T>(ref T a, ref T b) {...}

• The compiler can infer generic method

p p ( , ) { }

type parameters:i t[]  1   {6  5  7  4  8  3  9  2  0  1}int[] array1 = {6, 5, 7, 4, 8, 3, 9, 2, 0, 1};int[] array2 = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};Sort<int>(array1); //Redundant( y ); //Swap(ref array1, ref array2); //Inference

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Page 7: Chapter 19 - Generics

MethodsGenerics 13C# 30

Methods

• Can access class type parameters:• Can access class type parameters:public class Matrix<T> {

public void Multiply(Vector<T> vector) { }public void Multiply(Vector<T> vector) {...}public void Multiply(Matrix<T> vector) {...}public Point Search(T element) {...} 

C if t i t

}

• Can specify constraints:public bool IsGreater<T>(T a, T b)

Can be overloaded on type parameters:

where T: IComparable<T> {...}

• Can be overloaded on type parameters:public void Method() {...}

bli   id M th d T () { }

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

public void Method<T>() {...}public void Method<T, U>() {...}

Generic DelegatesGenerics 14C# 30

Generic Delegates

• Generic delegates are defined as methods• Generic delegates are defined as methods and created as types:public delegate void StrategyHandler<T>(T param);public void CountStrategy(int count) {...}

bli   id R fSt t (R f f ) { }public void RefStrategy(Reference reference) {...}...StrategyHandler<int> counting = new gy g

StrategyHandler<int>(CountStrategy);StrategyHandler<Reference> referencing = new 

St t H dl <R f >(R fSt t )StrategyHandler<Reference>(RefStrategy);//Or, use C# 2.0 method group syntax:StrategyHandler<int> counting = CountStrategy;gy g gy;StrategyHandler<Reference> referencing = 

RefStrategy;

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Page 8: Chapter 19 - Generics

Default ValueGenerics 15C# 30

Default Value

• The default keyword will return null for• The default keyword will return null for reference types and zero-equivalent for

i l tnumeric value types• For structs it will return each member ofFor structs, it will return each member of

the struct initialized to zero or null

Debug.Assert(default(string) == null);Debug.Assert(default(float) == 0.0f);g ( ( ) )Debug.Assert(default(Point) == new Point(0, 0));

//Can use default(T) in a generic type/method//Can use default(T) in a generic type/method

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Generics and RuntimeGenerics 16C# 30

Generics and Runtime

Generic T pes are first class r n time• Generic Types are first-class run-time citizens– The compiler checks constraints and emits generic

types to metadatatypes to metadata

• The loader and JIT create and compile the necessary closed types at runtime– All reference type instantiation of X<T> share the yp

same JIT representation

– Each value type instantiation of X<T> gets its ownEach value type instantiation of X<T> gets its own compiled representation

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Page 9: Chapter 19 - Generics

Generic ExtensionsGenerics 17C# 30

Generic Extensions

Man BCL classes offer generic methods• Many BCL classes offer generic methods:

int[] array = { 6  5  7  4  8  3  9  2  0  1 };int[] array = { 6, 5, 7, 4, 8, 3, 9, 2, 0, 1 };

Array.Sort<int>(array);

int index = Array.BinarySearch<int>(array, 5);

– As with any generic method, specifying the type y g , p y g ypargument is redundant

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Generics and MetadataGenerics 18C# 30

Generics and Metadata

Generics are represented in metadata• Generics are represented in metadata:

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Page 10: Chapter 19 - Generics

Generics and ReflectionGenerics 19C# 30

Generics and ReflectionMethod Descriptionp

Type.GetGenericArguments Returns an array of Type objects that represent the bound arguments of a constructed type or the type parameters of an unconstructed type.

Type.GetGenericTypeDefinition Returns the underlying generic type definition for a specified constructed type.

Type GetGenericParameterConstraints Returns an array of Type objects that represent theType.GetGenericParameterConstraints Returns an array of Type objects that represent the constraints on the current generic type parameter.

Type.GenericParameterPosition For a Type object that represents a type parameter of a generic type definition or an open constructed type, gets g yp p yp , gthe position of the type parameter in the type parameter list of the generic type that declared the parameter.

Type.IsGenericTypeDefinition Returns true if the type has any unbound type y y y y yparameters. A closed constructed generic type will return false.

Type.IsGenericParameter Gets a value that indicates whether the current Type represents an unbound type parameter of a generic type or method.

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Generics and AttributesGenerics 20C# 30

Generics and Attributes

Attrib tes can be applied to generic t pes• Attributes can be applied to generic types in the same way as non-generic typesy g yp– Custom attributes are permitted to reference open

generic typesgeneric types

– Custom attributes are permitted to reference closed constructed generic typesconstructed generic types

[assembly:TypeFactoryAttribute(typeof(CustomerTypeFactory<>))]TypeFactoryAttribute(typeof(CustomerTypeFactory<>))]

[Presentation(typeof(MatrixView<Dimension.Three>))]bli l i { }public class Matrix<T> {...}

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Page 11: Chapter 19 - Generics

C# Generics vs C++ TemplatesGenerics 21C# 30

C# Generics vs. C++ Templates

• C# generics are a run time mechanism• C# generics are a run-time mechanism• C++ templates are a pure compile-time p p p

mechanism (smart macros)• Some C++ functionality is not available:• Some C++ functionality is not available:

– Non-type template parameters– Explicit and partial specialization– Type parameters can’t be used as a base class for a

i tgeneric type– Type parameters can’t have default values

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

SummaryGenerics 22C# 30

Summary

Generics pro ide re sabilit t pe safet• Generics provide reusability, type safety and efficiencyy

• Generics are most commonly used with ll ti d d t d i l ithcollections and data-driven algorithms

• Generics provide static polymorphismGenerics provide static polymorphism

• Generics are represented in metadata and can be queried using Reflection

© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel