You can see part 1 here, part 2.1 here and part 2.2 here
This is the second feature in this series that has an equivalent in C++ which called template parameters. Although there is a lot of differences between both but they still have the same usage. in case you are interested to know the difference you can check this out.
Generics came for the same purpose the template parameters in C++ came for. Write one function for different types, later the unknown type will be bound on compiling time.
Before Generics we get used to write this code
1 public class Stack
2 {
3 object[] _items;
4 public void Push(object item)
5 {
6
7 }
8 public object Pop()
9 {
10
11 }
12 }
13
14 class Program
15 {
16 static void Main()
17 {
18 Stack stack = new Stack();
19 stack.Push(1);
20 stack.Push(2);
21 int number = (int)stack.Pop();
22 }
23 }
24
For every line in the main method we have Boxing or Unboxing operation which has an effect on the preformace.
if we re-write the above code using generics it will look like this:
1 public class Stack <T>
2 {
3 T[] _items;
4 public void Push(T item)
5 {
6
7 }
8 public T Pop()
9 {
10
11 }
12 }
13
14 class Program
15 {
16 static void Main()
17 {
18 Stack<int> stack = new Stack<int>();
19 stack.Push(1);
20 stack.Push(2);
21 int number = stack.Pop();
22 }
23 }
The other feature beside the performance I see that Generics also promotes usability and it is type safe.
One last thing I like about Generics is that I can add constrain on the type that will be passed to the class. For example, if I am implementing search function using a key to search with, in this case the type of the key should implement the IComparable interface so that i can use it in comparison expressions. The header will look like this one
class Stack <T> where T : IComparable
The where used is a new keyword in C# 2.0