Documente Academic
Documente Profesional
Documente Cultură
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
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
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>
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
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){...}
) {
}
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>{...}
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
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
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
C# 30
Generics 19
Description
p
Type.GetGenericArguments
Type.GetGenericTypeDefinition
Type GetGenericParameterConstraints
Type.GetGenericParameterConstraints
Type.GenericParameterPosition
Type.IsGenericTypeDefinition
y
y
Type.IsGenericParameter
Copyright SELA Software & Education Labs Ltd. 14-18 Baruch Hirsch St. Bnei Brak 51202 Israel
C# 30
Generics 20
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