Friday, November 10, 2006

(ZT) Generic Classes Example in C# 2.0

Basically Generic class in C# is similar template in C++ .

Primay difference :

C# generic type substituions are performed in running time and generic type information is preserved for the instantiated objects. 

 

The example shown below is a simple generic linked list class for demonstration purpose :

Class:

using System;
using System.Collections.Generic;


public class MyList<T> //type parameter T in angle brackets
{
private Node head;
// The nested class is also generic on T.
private class Node
{
private Node next;
//T as private member data type:
private T data;
//T used in non-generic constructor:
public Node(T t)
{
next = null;
data = t;
}

public Node Next
{
get { return next; }
set { next = value; }
}
//T as return type of property:
public T Data
{
get { return data; }
set { data = value; }
}
}
public MyList()
{
head = null;
}
//T as method parameter type:
public void AddHead(T t)
{
Node n = new Node(t);
n.Next = head;
head = n;
}
public IEnumerator<T> GetEnumerator()
{
Node current = head;
while (current != null)
{
yield return current.Data;
current = current.Next;
}
}

}

 

 

Test App:

 

class Program
{
static void Main(string[] args)
{
//int is the type argument.
MyList<int> list = new MyList<int>();

for (int x = 0; x < 10; x++)
list.AddHead(x);
foreach (int i in list)
Console.WriteLine(i);
Console.WriteLine("Done");
}
}

0 Comments:

Post a Comment

<< Home