C# 2.0 : How to create Generics
Posted by
hungle
Labels:
Dot Net
Generic Class with one parameter
This is a typical Non-generic Class :public class ListGeneric Class : in order to create generics class we use the type argument T in < and > after class name.
{
object[] items;
public void Add(object item) {....}
public object this[int index] {...}
}
public class List<T>Using Generic class :
{
[T] items;
public void Add(T item) {....}
public T this[int index] {...}
}
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
Generic Class with more than one parameters
Generic type declarations may have any number of type parameters. The Listpublic class Dictionary<K,V>When Dictionary
{
public void Add(K key, V value) {...}
public V this[K key] {...}
}
Dictionary<string, Customer> dict =
new Dictionary<string, Customer>();
dict.Add("Hung", new Customer());
Customer customer = dict["Hung"];
blog comments powered by Disqus
Subscribe to:
Post Comments (Atom)