Could some one tell me why I am getting a syntax error when I try to implement the CompareTo() interface. I am getting an error which seems to say that It could not find my code for the compareTo() method in my school class. I think I am doing something wrong in terms of inheritance. If I could just fix the syntax error I could get the rest of the code to work.
The program below accepts 5 school objects. Each object takes the name of the school and the enrollment size. I am suppose to sort each school by enrollment using the CompareTo() Method which is suppose to be implemented using the ICompare interface. The code is below:
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Chapt9_Exe8A
//this is my school class which implements the IComparable interface
class School: IComparable
{
public string name {get;set;}
public int enrollSize {get;set;}
public School()
{
name = null;
enrollSize = 0;
}
public School(string name, int enrollSize)
{
this.name = name;
this.enrollSize = enrollSize;
}
/*This is the CompareTo() method implementation it returns integer. 1 if this.enroll is larger than what is passed in the CompareTo method, -1 if this is less, and 0 if they are the same*/
public int IComparable.CompareTo(School s)
{
int returnVal;
School temp = s;
if (this.enrollSize > temp.enrollSize)
returnVal = 1;
else
if (this.enrollSize < temp.enrollSize)
returnVal = -1;
else
returnVal = 0;
return returnVal;
}
}
/*This is my SchoolDemo class. It accepts the required information form the user and builds the five objects. It is suppose to display the information in the correct order but, I've haven't got around to coding that yet.*/
class SchoolsDemo: School
{
static void Main(string[] args)
{
School[] schoolArray = new School [5];
School schoolTemp = new School();
Console.WriteLine("This program will ask you for the name and enrollment of five schools"
+ "then sort you input");
for (int i = 0; i <= 5; ++i)
{
Console.WriteLine("Please enter name of {0}st school: ", i + 1);
string name = Console.ReadLine();
Console.WriteLine("Please enter enrollment size: ");
int enrollSize = Convert.ToInt32(Console.ReadLine());
schoolArray [i] = new School (name, enrollSize);
}
int b = 1;
for (int a =0; a < 5; ++a){
++b;
for (int i = 0; i < 5; ++i)
{
int answer = schoolArray[a].CompareTo(schoolArray[i+b]);
if (answer == 1)
{
schoolTemp = schoolArray[i+b];
schoolArray[i+b] = schoolArray[a];
schoolArray[a] = schoolTemp;
if ((i + b) == 4)
break;
}
}
}
}
}
}