Generics in C# 2.0

Generics refer to classes and methods that work uniformly on values of different types. Generics allow you to define type-safe classes without compromising type safety, performance, or productivity. You implement the server only once as a generic server, while at the same time you can declare and use it with any type. To do that, use the < and > brackets, enclosing a generic type parameter.

Here is some sample implementation. It is Generic Stack class already available in System.Collections.Generic

public class Stack<T>
{
    T[] items;
    int currentIndex = 0;
    public Stack(int size)
    {
        items = new T[size];
    }
    public void Push(T item)
    {
        this.items[currentIndex] = item;
        this.currentIndex++;
    }
    public T Pop()
    {
        if (this.currentIndex < 0)
        {
            throw new IndexOutOfRangeException();
        }
        return this.items[this.currentIndex];
    }
}

And you can use the stack like this.

Stack<int> stack = new Stack<int>(10);
stack.Push(100);
int number = stack.Pop();

For more information check this URL :
http://msdn2.microsoft.com/en-us/library/ms379564(VS.80).aspx

No related content found.

This entry was posted in .Net and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*


*

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>