Skip navigation

It’s a quite easy to sort scalar types like String, Integer etc using Array.Sort. But we might require sorting capabilities on custom classes that we code.

The IComparable interface defines a method, which needs to be implemented to create comparison method for specific types and classes. The class or type needs to implement CompareTo method in order to have sorting capabilities.

 

Briefly, the user defined class needs to inherit IComparable interface and implement the CompareTo method in order to have sorting capabilities. The CompareTo method takes a single parameter of type Object. It is expected that an object of the same class be passed to this method. If not, the exception has to be handled by the implementing method.

 

Here are the three conditions that need to be implemented

  • If the current instance is lesser than the passed object instance, then we return a value lesser than 0.
  • If the current instance is equal to the passed object instance, then we return 0.
  • If the current instance is greater to the passed object instance, then we return a value greater than 0

 

We will look at how the student object can be sorted on basis of his Roll Call Number.

 

Given below is the code

 

using System;

 

namespace MyCsClassLibrary

{

      /// <summary>

      /// Summary description for Student.

      /// </summary>

      public class Student:IComparable

      {

            int iRollNo ;

           

            public Student(int RollNo)

            {

                  iRollNo = RollNo ;

 

            }

            public int CompareTo(object obj)

            {

                  Student myObj ;

                  try

                  {

                        myObj = (Student)obj ;

                  }

                  catch(Exception ex)

                  {

                        throw new Exception("Object Passed is not Student",ex);

                  }

                 

                  if(this.iRollNo > myObj.iRollNo)

                  {

                        //return a value greater than 0

                        return 1;

                  }

                  else if(this.iRollNo == myObj.iRollNo)

                  {

                        return 0 ;

                  }

                  else

                  {

                        return -1 ;

                  }

            }

 

      }

}

 

 

Happy Coding !!!

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish