Monday, October 18, 2004

C# Generics

I recently installed Visual Studio Whidbey Beta 1 (which i recieved through MS Community Starter KIT) on my machine. It is kind of a cool ide with lots of enhancements like Refactoring and Expansions. I wrote my first program implementing the concepts of Generics. Generics are a new feature of .Net Framework 2.0. With Generics we can defer type specification of one or more type until the class is declared and instantiated by the client code. This effectively translates into Templates Concept of C++.

I implemented a generic stack class and the code goes like this:

public class Stack
{
///
/// Top of the Stack
///

private int top;

///
/// Generic Collection to hold stack contents
///

private System.Collections.Generic.Collection data;


///
/// Stack Constructor
///

///
public Stack(System.Collections.Generic.Collection t)
{
data = t;
top = 0;
}

///
/// Default Constructor
///

public Stack()
{
data = new System.Collections.Generic.Collection();
top = 0;
}

///
/// Push
///

/// Item/Content to be pushed
public void push(T item)
{
data.Insert(top,item);
top++;
}

///
/// POP
///

/// Content / Item on stack top
public T pop()
{
if (top > 0)
{
top = top - 1;
return data[top];
}
else
{
throw new IndexOutOfRangeException(" Stack is already empty");
}
}

}
#endregion

#region Testing Stack Class
///
/// Testing Stack Class
///

class Program
{
static void Main(string[] args)
{
// Stack Class Object -- See char as type paramter..
//(this reminds me of C++ :))
Stack myStack = new Stack();

myStack.push('H');
myStack.push('A');
myStack.push('M');

Console.WriteLine(myStack.pop().ToString());
Console.WriteLine(myStack.pop().ToString());
Console.WriteLine(myStack.pop().ToString());

// Index Out of Bound Exception
Console.WriteLine(myStack.pop().ToString());

Console.ReadLine();
}
}
#endregion
}


This code wont get me any accoldate, that I know :). But it still proves the point that Generics are simple and very useful in terms of re-usable data structures.

No comments: