namespace GenericsusingLinkedList_25_03 { // Test the CustomList class TestCustomList { static void Main() { // Declare a List of type int, then loop through the List CustomList<int> list1 = new CustomList<int>(); for (int x = 1; x <= 3; x++) { list1.Add(x); } foreach (int i in list1) { System.Console.Write(i + " "); } Console.ReadKey(); } } public class CustomList<t> { // Fields private Node head=null; // The nested class is also generic on T private class Node { // Fields private Node next; // T as private member data type private T data; // Properties public Node Next { get { return next; } set { next = value; } } // T as return type of the Property public T Data { get { return data; } set { data = value; } } // T used in non-generic constructor public Node(T pData) { this.next = null; this.data = pData; } } // T as method parameter type: public void Add(T pType) { Node n = new Node(pType); n.Next = head; //next of current node is assigned head of previous node this.head = n; //head of current is same as n } // Enables foreach on the List public IEnumerator<t> GetEnumerator() { Node current = head; while (current != null) { yield return current.Data; current = current.Next; } } } }
yield return current.Data;
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)