static void Main(string[] args) { // create some objects to use for testing Prob5Class pc1 = new Prob5Class("Damian Lillard", 0); Prob5Class pc2 = new Prob5Class("CJ McCollum", 3); Prob5Class pc3 = new Prob5Class("Damian Lillard", 3); Prob5Class pc4 = new Prob5Class("CJ McCollum", 0); Prob5Class pc5 = new Prob5Class("Jusef Nurkic", 0); Prob5Class pc6 = new Prob5Class("Jusef Nurkic", 3); // test logic - expect positive, i.e. B follows A Console.WriteLine(pc1.CompareTo(pc2)); Console.WriteLine(); // put test objects in array Prob5Class[] pcArray = new Prob5Class[6]; pcArray[0] = pc1; pcArray[1] = pc2; pcArray[2] = pc3; pcArray[3] = pc4; pcArray[4] = pc5; pcArray[5] = pc6; // sort array Array.Sort(pcArray); // print sorted array foreach (Prob5Class element in pcArray) { Console.WriteLine(element); } }
// interface method // Objects in the class should be ordered in the following manner: // * primary sort order is alphabetical according to the text field // * secondary sort order is largest first according to the int field // int IComparable.CompareTo(object obj) public int CompareTo(object obj) { // cast obj to Prob5Class type Prob5Class pc = obj as Prob5Class; // if cast is successful make comparisons if (pc != null) { // return value corresponding to comparison if (String.Compare(this.PcStr, pc.PcStr) < 0) { return(-1); } if (String.Compare(this.PcStr, pc.PcStr) > 0) { return(1); } else // strings are the same..compare ints { if (this.PcInt < pc.PcInt) { return(-1); } if (this.PcInt > pc.PcInt) { return(1); } else { return(0); } } } else { throw new ArgumentException("Parameter is not a Prob5Class object "); } }