I recently installed Visual Studio Whidbey Beta 1 (which i received 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:
#region
Using directives
using
System;
using
System.Collections.Generic;
using
System.Text;
#endregion
namespace
helloGenerics
{
#region
Stack Class
/// <summary>
/// My Simple Stack Class using Generics
/// </summary>
/// <typeparam name="T">Type Parameter</typeparam>
public class Stack<T>
{
/// <summary>
/// Top of the Stack
/// </summary>
private int top;
/// <summary>
/// Generic Collection to hold stack contents
/// </summary>
private System.Collections.Generic.Collection<T> data;
/// <summary>
/// Stack Constructor
/// </summary>
/// <param name="t"></param>
public Stack(System.Collections.Generic.Collection<T> t)
{
data = t;
top = 0;
}
/// <summary>
/// Default Constructor
/// </summary>
public Stack()
{
data =
new System.Collections.Generic.Collection<T>();
top = 0;
}
/// <summary>
/// Push
/// </summary>
/// <param name="item">Item/Content to be pushed</param>
public void push(T item)
{
data.Insert(top,item);
top++;
}
/// <summary>
/// POP
/// </summary>
/// <returns>Content / Item on stack top</returns>
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
/// <summary>
/// Testing Stack Class
/// </summary>
class Program
{
static void Main(string[] args)
{
// Stack Class Object -- See char as type paramter.. (this reminds me of C++ :))
Stack<char> myStack = new Stack<char>();
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 accolades, that I know :). But it still proves the point that Generics are simple and very useful in terms of re-usable data structures.
Hammad Rajjoub.
UG Leader and Member Speakers Bureau,
Ineta Pakistan.
http://dotnetwizards.blogspot.com