// Copyright (c) Microsoft Corporation. All Rights Reserved.
Using system.collections; usner; using system.text;
Namespace generics_csharp {// type parameter t in Angle Brackets. Public class mylist
// nested type is also generic on t protected class node {public node next; // t as private mer; // t used in non-generic constructor. Public node (t t) {next = null; Data = T;} public node next {get {return next;}} // t as return type} // t as return type} // T Data {Get {Return Data;} set {data = value;}}} }
Public mylist () {head = null;
// t as method parameter type. Public void addhead (t) {node n = new node (t); n.next = head; Head = n;}
// Implement GetEnumerator to return IEnumerator
while (current = null!) {yield return current.Data; current = current.Next;}} // We must implement this method because // IEnumerable
Public class sortedlist
Bool swapped; do {node previous = null; node current = head; swapped = false;
While (current.next! = null) {// Because We need to call this method, the sortedlist // Class IS constrained on inumerable
IF (previous == null) {head = tmp;} else {previous.next = TMP;} previous = tmp; swapped = true;
Else {previous = current; current = current.next;}} // end while} while (swapped);}}
// A simple class that implements IComparable
Public Person (String S, INT I) {Name = S; AGE = I;
// this will cause list elements // to be sorted on age value. Public int compareto (Person P) {RETURN AGE - P.AGE;}
Public override string toString () {return name ":" AGE;
// Must Implement Equals. Public Bool Equals (Person P) {Return (this.age == P.AGE);}}
Class generics {static void main (string [] args) {// declare and instantiate a new generic sortedlist class. // Person is the Type Argument. sortedlist
// Create name and age value to initialize Person Objects. String [] names = new string [] {"Franscoise", "Bill", "Li", "Sandra", "Gunnar", "Alok", "Hiroyuki", "Maria", "Alessandro", "raul"}; int [] Ages = new int [] {45, 19, 28, 23, 18, 9, 108, 72, 30, 35};
// Populate the list. For (int x = 0; x // sort the list. List.bubblesort (); Console.Writeline ("{0} sorted list:", environment.newline)); //print out sorted list. Foreach (Person P in list) {console.writeline (p.tostring ());} Console.writeline ("DONE");}} } CSC generics.cs generics