Skip to content

Instantly share code, notes, and snippets.

@AndrewBarfield
Created April 30, 2012 08:18
Show Gist options
  • Save AndrewBarfield/2556506 to your computer and use it in GitHub Desktop.
Save AndrewBarfield/2556506 to your computer and use it in GitHub Desktop.
C#: System.Collections.Generic: Custom Generic list class
using System;
using System.Collections.Generic;
namespace GenericList {
class Program {
static void Main(string[] args) {
// int is the type argument
GenericList<int> list = new GenericList<int>();
for ( int x = 0 ; x < 10 ; x++ ) {
list.AddHead( x );
}
foreach ( int i in list ) {
System.Console.Write( i + " " );
}
System.Console.WriteLine( "\nDone" );
Console.Read();
}
}
// type parameter T in angle brackets
public class GenericList<T> {
// The nested class is also generic on T.
private class Node {
// T used in non-generic constructor.
public Node(T t) {
next = null;
data = t;
}
private Node next;
public Node Next {
get { return next; }
set { next = value; }
}
// T as private member data type.
private T data;
// T as return type of property.
public T Data {
get { return data; }
set { data = value; }
}
}
private Node head;
// constructor
public GenericList() {
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;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment