You are on page 1of 11

C# 30

Generics 1

C# 3.0
Chapter 19 – Generics

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

C# 30

Generics 2

Introduction
• Generic code is vital
ital for creating
g
collections and common algorithms
– Often reusability is ignored just because the data type
is not the same

• Polymorphism can help, but:
– Often comes with a performance penalty
– Can’t control existing
g types
yp that don’t implement
p
an
interface or override a virtual method

• Generics are key to reusable and efficient
code
© Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Add(new Employee("Steve". l Add(  E l ("St "  "B ll ")) // return value must be cast down Employee employee p y p y = (Employee)employees[0]. "Ballmer")). employees. ( p y ) p y [ ]. • Generic collection: List<Employee> employees = new List<Employee>(). polygon Add(new Point(0  0)). 14-18 Baruch Hirsch St.   "Ballmer")). Ballmer )). //Unboxing! • Generic collection: List<Point> polygon = new List<Point>().Add(new Employee( Steve . employees Add(new Employee("Steve" employees.Add(new Point(0. l Add(  P i t(0  0)) //B i ! //Boxing! Point p = (Point)polygon[0].C# 30 Generics 3 Motivation: Collections • Non generic collection: ArrayList employees = new ArrayList(). polygon.Add(new Point(0. //No unboxing © Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. //No boxing Point p = polygon[0]. // return value is guaranteed to be Employee Employee employee = employees[0]. polygon. 0)). Bnei Brak 51202 Israel C# 30 Generics 4 Motivation: Collections • Non generic collection: ArrayList polygon = new ArrayList(). Bnei Brak 51202 Israel . 0)). © Copyright SELA Software & Education Labs Ltd.

14-18 Baruch Hirsch St. M t i Matrix<string> t i stringMatrix t i M t i = new Matrix<string>(). as cast to interfaces / base classes and work with that – This is not compile-time compile time safe: Code can break at run runtime. © Copyright SELA Software & Education Labs Ltd..    M t i t i () Matrix<Cmd> cmdMatrix = new Matrix<Cmd>().. Bnei Brak 51202 Israel C# 30 Generics 6 Generic Constraints • Generic code can’t assume ass me an anything thing yp p parameter about the type – Except that it derives from Object • One alternative is to use is and as. Bnei Brak 51202 Israel .. 14-18 Baruch Hirsch St. there is no good contract with the client • Another A th alternative lt ti iis constraints t i t – Get you type y compile-time p yp safety! y © Copyright SELA Software & Education Labs Ltd.} { } • Client code: Matrix<int> intMatrix = new Matrix<int>().C# 30 Generics 5 Generic Types • Generic types have type parameters – Placeholders that will be replaced with the data type specified by client code public class Matrix<T> {..} public interface IVector<T> bli  i t f  IV t T {.

f The constraining interface/s can also l b be generic i © Copyright SELA Software & Education Labs Ltd.Print(). 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel C# 30 Generics 8 Constraints Combined public class Matrix<T> where T : class.WriteLine(). IPrintable<T>.C# 30 Generics 7 Defining Constraints Constraint where T : struct where T : class where T : new() Description yp T must be a value-type T must be a reference type T must have a public public. Console. new() { public void Print() { foreach (T[] row in _rows) { foreach (T printable in row) printable. default ctor (appears last) where here T : <base> T must m st be or deri derive e from base where T : <interface> T must be or implement interface. Bnei Brak 51202 Israel . } } } © Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St.

Bnei Brak 51202 Israel C# 30 Generics 10 Inheritance Issues • Generic classes can inherit from open generic classes or concrete types: public class Matrix<T> : BaseMatrix {...C# 30 Generics 9 Unbounded Type Parameter • Without Witho t constraints we e are very er limited: limited – The != and == operators cannot be used – They can be converted to and from object or explicitly converted to any y interface type yp – They can be compared to null but the comparison will always return false if the type argument is a value type © Copyright SELA Software & Education Labs Ltd.} public class Matrix<T> : BaseMatrix<T> {.} © Copyright SELA Software & Education Labs Ltd.} //D ’t  il //Doesn’t compile public class MatrixEx : Matrix<T> {.. Bnei Brak 51202 Israel .. 14-18 Baruch Hirsch St.} • Non-generic Non generic classes can inherit from closed generic classes: //OK public class IntMatrix : Matrix<int> {..} public class Matrix<T> : BaseMatrix<int> {..... 14-18 Baruch Hirsch St..

p ( ). T b) {. 3. 4. 1. 14-18 Baruch Hirsch St. 14-18 Baruch Hirsch St. 7. 4... 1}.} public void Swap<T>(ref p p ( T a. Bnei Brak 51202 Israel C# 30 Generics 12 Generic Methods • A generic method is a method that is declared with type yp parameters. 2.} • The Th same inheritance i h i rules l apply l © Copyright SELA Software & Education Labs Ltd. 0. IEquatable<T> {. //Inference © Copyright SELA Software & Education Labs Ltd. Sort<int>(array1). 9.} ) { } • The compiler can infer generic method type parameters: int[] array1 = {6. 3. // //Redundant Swap(ref array1. 5. ref . p public void Sort<T>(T[] array2Sort) {. 6. i t[]  1   {6  5  7  4  8  3  9  2  0  1} int[] array2 = {0. 8.C# 30 Generics 11 Interfaces • Use generic interfaces to avoid a oid bo boxing ing and unboxing (value types) public interface IComparable<T> { int CompareTo(T other). 2. ref array2). 9}. Bnei Brak 51202 Israel . } public class Matrix<T> where p blic class Matri <T>  here T : IComparable<T>. 7. 8... ( y )... 5.

.. StrategyHandler<Reference> referencing = new  St t StrategyHandler<Reference>(RefStrategy).. U>() {. T b) where T: IComparable<T> {.} public void bli   id Method<T>() {... 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel .. use C# 2.} • Can be overloaded on type parameters: public void Method() {...} f ) { } .} public void bli   id RefStrategy(Reference R fSt t (R f reference) {.} public Point Search(T element) {.} © Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St.} Multiply(Vector<T> vector) { } public void Multiply(Matrix<T> vector) {... H dl <R f >(R fSt t ) //Or.. Bnei Brak 51202 Israel C# 30 Generics 14 Generic Delegates • Generic delegates are defined as methods and created as types: public delegate void StrategyHandler<T>(T param)....0 method group syntax: StrategyHandler<int> counting gy g = CountStrategy.. gy.}  } • Can C specify if constraints: t i t public bool IsGreater<T>(T a.} M th d T () { } public void Method<T.....C# 30 Generics 13 Methods • Can access class type parameters: public class Matrix<T> { public void Multiply(Vector<T> vector) {. StrategyHandler<int> counting gy g = new  StrategyHandler<int>(CountStrategy). © Copyright SELA Software & Education Labs Ltd.. public void CountStrategy(int count) {. StrategyHandler<Reference> referencing =  RefStrategy.

C# 30 Generics 15 Default Value • The default keyword will return null for reference types and zero-equivalent for numeric i value l types t • For structs. 14-18 Baruch Hirsch St.Assert(default(Point) == new Point(0. Bnei Brak 51202 Israel C# 30 Generics 16 Generics and Runtime • Generic Types T pes are first-class first class rrun-time n time citizens – The compiler checks constraints and emits generic types to metadata • The loader and JIT create and compile the necessary closed types at runtime – All reference type yp instantiation of X<T> share the same JIT representation – Each value type instantiation of X<T> gets its own compiled representation © Copyright SELA Software & Education Labs Ltd. Bnei Brak 51202 Israel . ) Debug. Debug. //Can use default(T) in a generic type/method © Copyright SELA Software & Education Labs Ltd. structs it will return each member of the struct initialized to zero or null Debug. 14-18 Baruch Hirsch St. 0)).Assert(default(string) == null).0f).Assert(default(float) g ( ( ) == 0.

 3. 8.. Bnei Brak 51202 Israel .BinarySearch<int>(array. 5). 14-18 Baruch Hirsch St. 14-18 Baruch Hirsch St. – As with any y generic g method. 5. 4. int[] array = { 6  5  7  4  8  3  9  2  0  1 }. 0. 9. 7. Array. specifying p y g the type yp argument is redundant © Copyright SELA Software & Education Labs Ltd. Bnei Brak 51202 Israel C# 30 Generics 18 Generics and Metadata • Generics are represented in metadata metadata: © Copyright SELA Software & Education Labs Ltd. 2. 1 }.C# 30 Generics 17 Generic Extensions • Man Many BCL classes offer generic methods methods: int[] array = { 6.Sort<int>(array). int index = Array.

Bnei Brak 51202 Israel C# 30 Generics 20 Generics and Attributes • Attrib Attributes tes can be applied to generic ttypes pes y as non-generic g types yp in the same way – Custom attributes are permitted to reference open generic types – Custom attributes are permitted to reference closed constructed generic types [assembly: TypeFactoryAttribute(typeof(CustomerTypeFactory<>))] [Presentation(typeof(MatrixView<Dimension. g gets the position of the type parameter in the type parameter list of the generic type that declared the parameter. 14-18 Baruch Hirsch St..GetGenericArguments Returns an array of Type objects that represent the bound arguments of a constructed type or the type parameters of an unconstructed type.C# 30 Generics 19 Generics and Reflection Method Description p Type.} © Copyright SELA Software & Education Labs Ltd.GetGenericParameterConstraints Returns an array of Type objects that represent the constraints on the current generic type parameter. Type.IsGenericParameter Gets a value that indicates whether the current Type represents an unbound type parameter of a generic type or method.IsGenericTypeDefinition y y Returns true if the type y has any y unbound type y parameters.GetGenericTypeDefinition Returns the underlying generic type definition for a specified constructed type.GenericParameterPosition For a Type object that represents a type parameter of a g generic type yp definition or an open p constructed type. Bnei Brak 51202 Israel .. 14-18 Baruch Hirsch St.Three>))] bli l i { } public class Matrix<T> {. Type GetGenericParameterConstraints Type. A closed constructed generic type will return false. © Copyright SELA Software & Education Labs Ltd. Type. Type. Type. yp .

re sabilit type t pe safet safety y and efficiency • Generics are most commonly used with collections ll ti and dd data-driven t di algorithms l ith • Generics provide static polymorphism • Generics are represented in metadata and can be queried using Reflection © Copyright SELA Software & Education Labs Ltd.C# 30 Generics 21 C# Generics vs vs. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel . 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel C# 30 Generics 22 Summary • Generics provide pro ide reusability. C++ Templates • C# generics are a run run-time time mechanism • C++ templates p are a p pure compile-time p mechanism (smart macros) • 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 generic i ttype – Type parameters can’t have default values © Copyright SELA Software & Education Labs Ltd.