- Generics allow us to create and use strongly type collections that are type-safe because we do not need to do casting of the elements nor do boxing and unboxing of value types.
- Generic classes is defined including the parameter type T in the declaration of the class or interface.
How to create a generic class
- Add the type parameter T between symbol minor and major ( < >) after the class's name.
- Use the type parameter T instead the data type names in the member classes.
- Each instance of T inside the class is replace with parameter type that we have provided.
- Specify the type that we want to pass as parameter type.
For example
In this example our list only allow object of type person if we want of other type we can create other list.
- One of the more commons and important use of the generics are in collection classes..
advantages of generics
The generic collections provide :
- Type safety: assure that we have a homogeneous collection,
- No casting: Casting is very expensive while generics improve the performance the application because add or read items do not need to do casting.
- No boxing and unboxing: they are long expensive and can make slow an application, specially in long collections
Generic list Collections .
Generic class list store collections in objects of type T
- List<T> : It is a list of generic use
- LinkedList<T>:it is list in which each item is linked to previous item and the next in the collection.
- Stack<T>: it is a collection last in, first out
- Queue<T>: it is a collection first in, first out
Generic Dictionary collections
It is dictionary classes that store pair key and value.
the key and the value are strongly types
- Dictionary<Tkey, TValue>:it is a generic dictionary to use general.
- SortedList<Tkey,TvalueZ>:
- SortedDictionary<TKey,Tvalue>: They are sort collections by key



No hay comentarios:
Publicar un comentario