Professional Documents
Culture Documents
Generics in C#
Generics in C#
Mechanisms
Inheritance
Generics
Base Type
Template
Type
Inheritance
Base Type
Reusable
Code
Car
NumberOfDoors
----------------UnlockDoors()
OpenDoor()
MountOnSeatBelt()
Vehicle
Color
Speed
----------------IngniteEngine()
Drive()
Fields
Methods
Motorcycle
Chain
------------------SitOnIt()
BendToSteer()
DoTheOneWeelTrick()
Generics
A template contains type parameters
<B>
Body
<E>
Engine
<C>
Chassis
<W>
Wheels
Template
SUV
<B>
Reusable
Code
<C>
<E>
<W>
Car
Ferrari
Type
A generic can be
Method()
Generic Type
public class Stack<T>
{
int position;
T[] data = new T[100];
public void Push(T obj){
data[position++] = obj;
}
public T Pop(){
return data[--position];
}
}
int
<T>
Stack<T>
int
Stack<int>
int
public class Stack<T>
{
int position;
T[] data = new T[100];
public T Pop(){
return data[--position];
}
open type
closed type
No downcast is required
Avoids the possibility of a runtime error
Eliminates the overhead of boxing/unboxing
Generic Method
static void Swap<T> (ref T a, ref T b)
{
T temp = a;
a = b;
b = temp;
}
int x = 5, y = 10;
Swap(ref x, ref y);
Generic Constraints
Can be applied to a type parameter
where T : base-class
where T : interface
where T : class
where T : struct
where T : new()
where U : T
class List<T>
{
void Add<U>(List<U> items) where U : T {/*...*/}
}
Covariance
Only interface and delegate type parameters can be
specified as variant
Covariant interface
The out modifier on T
indicates that
T is used only in
output positions
(e.g., return types for methods)
Bear
99
Bear
2
Bear
1
Bear
The out modifier on T indicates that T is used only in output positions (e.g.,
return types for methods)
bears
animals
class Animal { }
class Mouse : Animal { }
class Elephant : Animal { }
Stack<Mouse> mice = new Stack<Mouse>();
Stack<Animal> animals = mice;
Compiler Error
Cannot implicitly convert type Stack<Mouse> to type Stack<Animal>