Maha

Maha

  • NA
  • 0
  • 312k

NP41 Why Casting

Sep 11 2007 9:44 AM

Hi Guys

 

NP41 Why Casting

 

Following program is a book exercise. IComparable.CompareTo() method included to sort school objects by enrollment. Here there is a casting,  I couldn’t uderstand the need for casting here. Any one know please explain.

 

School temp = (School)o;   

 

Thank you

 

using System;

public class SchoolCompare

{

    public static void Main()

    {

        School[] school = new School[8];

 

        for (int x = 0; x < school.Length; ++x)

        {

            school[x] = new School();

 

            Console.Write("Name of School #{0} ", x + 1);

            school[x].SchoolName = Console.ReadLine();

 

            Console.Write("Students Enrollment Nnuber: ");

            school[x].StudentEnrolled = Convert.ToInt32(Console.ReadLine());

 

            Console.WriteLine();

        }

 

        Array.Sort(school);

 

        for (int x = 0; x < school.Length; ++x)

            Console.WriteLine("School #{0} , Name: {1}, Enrollement Number: {2}",

                            x + 1, school[x].SchoolName, school[x].StudentEnrolled);

    }

}

class School : IComparable

{

    private string sName;

    private int enrolled;

 

    public string SchoolName

    {

        get { return sName; }

        set { sName = value; }

    }

    public int StudentEnrolled

    {

        get { return enrolled; }

        set { enrolled = value; }

    }

 

    public int CompareTo(Object o)

    {

        int returnVal;

        School temp = (School)o;

 

        if (this.enrolled > temp.enrolled)     

            returnVal = 1;

        else

            if (this.enrolled < temp.enrolled)

                returnVal = -1;

            else

                returnVal = 0;

 

        return returnVal;

    }

}


Answers (5)