example use of generics in csharp

Generics in C# allow methods and classes to be parameterized by type.

Below is an example of a generic method that swaps two values of any type:

main.cs
public static void Swap<T>(ref T a, ref T b)
{
    T temp = a;
    a = b;
    b = temp;
}
90 chars
7 lines

In this example, T is the generic type parameter.

Now, we can use this method to swap integers:

main.cs
int x = 1;
int y = 2;
Swap<int>(ref x, ref y);
47 chars
4 lines

We can also use it to swap strings:

main.cs
string s1 = "hello";
string s2 = "world";
Swap<string>(ref s1, ref s2);
72 chars
4 lines

And this is an example of a generic class Stack<T> that can hold any type of object:

main.cs
public class Stack<T>
{
    private T[] elements;
    private int top = -1;

    public Stack(int size)
    {
        elements = new T[size];
    }

    public void Push(T element)
    {
        if (top == elements.Length - 1)
            throw new InvalidOperationException("Stack overflow");
        elements[++top] = element;
    }

    public T Pop()
    {
        if (top == -1)
            throw new InvalidOperationException("Stack empty");
        return elements[top--];
    }
}
488 chars
25 lines

We can now create a stack of integers:

main.cs
Stack<int> intStack = new Stack<int>(10);
intStack.Push(1);
intStack.Push(2);
intStack.Push(3);
int x = intStack.Pop(); // x == 3
130 chars
6 lines

Or a stack of strings:

main.cs
Stack<string> stringStack = new Stack<string>(10);
stringStack.Push("hello");
stringStack.Push("world");
string s = stringStack.Pop(); // s == "world"
151 chars
5 lines

related categories

gistlibby LogSnag