Sie sind auf Seite 1von 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
Cant control existing
g types
yp that dont 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

C# 30

Generics 3

Motivation: Collections
Non generic collection:
ArrayList employees=newArrayList();
employees.Add(newEmployee("Steve","Ballmer"));
l
Add(
E l
("St
" "B ll
"))
//returnvaluemustbecastdown
Employeeemployee
p y
p y
=(Employee)employees[0];
( p y ) p y
[ ];

Generic collection:
List<Employee>employees=newList<Employee>();
employees Add(newEmployee("Steve"
employees.Add(newEmployee(
Steve ,
"Ballmer"));
Ballmer ));
//returnvalueisguaranteedtobeEmployee
Employeeemployee =employees[0];

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

C# 30

Generics 4

Motivation: Collections
Non generic collection:
ArrayList polygon=newArrayList();
polygon.Add(newPoint(0,0));
l
Add(
P i t(0 0))
//B i !
//Boxing!
Pointp=(Point)polygon[0];
//Unboxing!

Generic collection:
List<Point>polygon=newList<Point>();
polygon Add(newPoint(0 0));
polygon.Add(newPoint(0,0));
//Noboxing
Pointp=polygon[0];
//Nounboxing

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

C# 30

Generics 5

Generic Types
Generic types have type parameters
Placeholders that will be replaced with the data type
specified by client code
publicclassMatrix<T> {...}
publicinterfaceIVector<T>
bli i t f
IV t
T {...}
{
}

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

M t i
t i
()
Matrix<Cmd> cmdMatrix =newMatrix<Cmd>();

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

C# 30

Generics 6

Generic Constraints
Generic code cant 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,


as cast
to interfaces / base classes and work with
that
This is not compile-time
compile time safe: Code can break at run
runtime, 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. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

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, 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.


f
The constraining interface/s can
also
l b
be generic
i

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

C# 30

Generics 8

Constraints Combined
publicclassMatrix<T>
whereT:class,IPrintable<T>,new()
{
publicvoidPrint()
{
foreach (T[]rowin_rows)
{
foreach (Tprintableinrow)
printable.Print();
Console.WriteLine();
}
}
}

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

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. 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:
publicclassMatrix<T>:BaseMatrix {...}
publicclassMatrix<T>:BaseMatrix<int>{...}
publicclassMatrix<T>:BaseMatrix<T>{...}

Non-generic
Non generic classes can inherit from
closed generic classes:
//OK
publicclassIntMatrix :Matrix<int>{...}
//D
t
il
//Doesntcompile
publicclassMatrixEx :Matrix<T>{...}

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

C# 30

Generics 11

Interfaces
Use generic interfaces to avoid
a oid bo
boxing
ing
and unboxing (value types)
publicinterfaceIComparable<T>{
int CompareTo(Tother);
p
(
);
}
publicclassMatrix<T>where
p blicclassMatri <T> here T:
IComparable<T>,IEquatable<T>{...}

The
Th same inheritance
i h i
rules
l apply
l

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

C# 30

Generics 12

Generic Methods
A generic method is a method that is
declared with type
yp parameters.
p
publicvoid Sort<T>(T[]array2Sort){...}
publicvoid Swap<T>(ref
p
p
(
Ta,ref
,
Tb){...}
) {
}

The compiler can infer generic method


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

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

C# 30

Generics 13

Methods
Can access class type parameters:
publicclassMatrix<T>{
publicvoid Multiply(Vector<T>vector){...}
Multiply(Vector<T>vector){
}
publicvoid Multiply(Matrix<T>vector){...}
publicPointSearch(Telement){...}
}

Can
C specify
if constraints:
t i t
publicbool IsGreater<T>(Ta,Tb)
where T:IComparable<T>{...}

Can be overloaded on type parameters:


publicvoid Method(){...}
publicvoid
bli id Method<T>(){...}
M th d T (){
}
publicvoid Method<T,U>(){...}
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

C# 30

Generics 14

Generic Delegates
Generic delegates are defined as methods
and created as types:
publicdelegate void StrategyHandler<T>(Tparam);
publicvoid CountStrategy(int count){...}
publicvoid
bli id RefStrategy(Reference
R fSt t
(R f
reference){...}
f
){
}
...
StrategyHandler<int>counting
gy
g =new
StrategyHandler<int>(CountStrategy);
StrategyHandler<Reference>referencing =new
St t
StrategyHandler<Reference>(RefStrategy);
H dl <R f
>(R fSt t
)
//Or,useC#2.0method groupsyntax:
StrategyHandler<int>counting
gy
g =CountStrategy;
gy;
StrategyHandler<Reference>referencing =
RefStrategy;

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

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,
structs it will return each member of
the struct initialized to zero or null
Debug.Assert(default(string) ==null);
Debug.Assert(default(float)
g
(
(
) ==0.0f);
)
Debug.Assert(default(Point) ==newPoint(0,0));
//Canusedefault(T) inageneric type/method

Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. 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. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

C# 30

Generics 17

Generic Extensions
Man
Many BCL classes offer generic methods
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
y generic
g
method,, specifying
p
y g the type
yp
argument is redundant

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

C# 30

Generics 18

Generics and Metadata


Generics are represented in metadata
metadata:

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

C# 30

Generics 19

Generics and Reflection


Method

Description
p

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
Type.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


g
generic
type
yp definition or an open
p constructed type,
yp , g
gets
the position of the type parameter in the type parameter
list of the generic type that declared the parameter.

Type.IsGenericTypeDefinition
y
y

Returns true if the type


y has any
y unbound type
y
parameters. 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

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.Three>))]
bli
l
i
{
}
publicclassMatrix<T>{...}

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

C# 30

Generics 21

C# Generics vs
vs. 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 cant be used as a base class for a
generic
i ttype
Type parameters cant have default values

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

C# 30

Generics 22

Summary
Generics provide
pro ide reusability,
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. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel

Das könnte Ihnen auch gefallen