Enter your email address:


feedburner count

C# 2.0 : How to create Generics

Labels:

Generic Class with one parameter

This is a typical Non-generic Class :
public class List
{
object[] items;

public void Add(object item) {....}
public object this[int index] {...}
}
Generic Class : in order to create generics class we use the type argument T in < and > after class name.
public class List<T>
{
[T] items;

public void Add(T item) {....}
public T this[int index] {...}
}
Using Generic class :
List<int> listInteger = new List<int>;
listInteger.Add(
1);
listInteger.Add(
2);
listInteger.Add(
3);
listInteger.Add(
new Customer()); // Compile-time error

Note:
T : type argument.
List : is List of Integer type. The List type is called a constructed type. Every occurrence of T is replaced with the type argument int. When an instance of List is created, the native storage of the items array is an int[] rather than object[]. If we add a Customer into List , then compiler will report error.

Generic Class with more than one parameters

Generic type declarations may have any number of type parameters. The List example above has only one type parameter, but a generic Dictionary class might have two type parameters, one for the type of keys and one for the type of values.

public class Dictionary<K,V>
{
public void Add(K key, V value) {...}
public V this[K key] {...}
}
When Dictionary is used, two type arguments would have to be supplied :

Dictionary<string, Customer> dict = 
new
Dictionary<string, Customer>();
dict.Add(
"Hung", new Customer());
Customer customer
= dict["Hung"];




blog comments powered by Disqus