Maha

Maha

  • NA
  • 0
  • 308.9k

Constructor and get and set method

Sep 30 2012 5:19 PM
In this program school name is implemented in the constructor method because school name is usually not subjected to changes. Number of student enrolled is subjected to changes therefore it is implemented in get and set method. But program is producing error signal. What way it can be fixed without changing the above mentioned concept.

using System;

namespace _111111111
{
class Program
{
static void Main(string[] args)
{
School[] school = new School[3];

school[0] = new School("AAAA");
school[1] = new School("BBBB");
school[2] = new School("CCCC");

for (int x = 0; x < school.Length; ++x)
{
school[x] = new School();

Console.Write("Enrollment No ");
school[x].setStudentEnrolled(int.Parse(Console.ReadLine()));
}

Console.WriteLine("Before Sort");

for (int x = 0; x < school.Length; ++x)
Console.WriteLine("Schoo Name {0} No of student {1}", school[x].getName(), school[x].getStudentEnrolled());

Array.Sort(school);

Console.WriteLine("After Sort");

for (int x = 0; x < school.Length; ++x)
Console.WriteLine("Schoo Name {0} No of student {1}", school[x].getName(), school[x].getStudentEnrolled());

Console.ReadKey();
}
}
}
class School : IComparable<School>
{
string schooName;
int studentEnrolled;

public School(string schooName)
{
this.schooName = schooName;
}

public string getName()
{
return schooName;
}

public void setStudentEnrolled(int studentEnrolled)
{
this.studentEnrolled = studentEnrolled;
}
public int getStudentEnrolled()
{
return studentEnrolled;
}

public int CompareTo(School o)
{
if (o is School)
{
School temp = (School)o;
return this.studentEnrolled.CompareTo(temp.studentEnrolled);
}
else
throw new ArgumentException("object is not a School");
}
}

Answers (2)