How to Use IComparable Interfaces in C#

No.of Views1573
Bookmarked0 times
Downloads 
Votes0
By  kirtan007   On  11 Sep 2010 11:09:21
Tag : CSharp , Miscellaneous
This article is targeted for the people who don't know how to use IComparable Interfaces .
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Introduction

In layman sense interface is class that containing methods without body and that without body methods we can implement in our class .if methods having no body then what is use of it? we can also directly write method in our class without implementing interface.

above question will be always there in the user who don't know when and how to use interface .Lets take one example to explain you this thing .Array class containing method that that sorts Arrays that are of Primitive type ...like int , float etc. but if you try to sort Array of Custom Type you have developed with Array.Sort() is it going to work ? well it will not going to work for it .so how to tell Sort() method How to Compare the Data Inside your custom type ? and Sort According to your custom conditions ?.

Here comes the interface in picture . Array.Sort() method uses CompareTo() method to Compare Two objects for sorting purpose so if we have interface that contain CompareTo() method than we can override that method to provide our own logic for comparison of object and it will be Taken in use by Array.Sort() method .CompareTo() method returns int according to comparison logic inside .

so now you are familiar how and when the interfaces are used.lets use the Interface Practically .I will show you how to Sort Student DataType Array with IComparable.if we implement IComparable interface that means that our Type is Comparable with operator like > < >=.I have Created a Class Student like below that Implements Interface IComparable

Code

class Student :IComparable
    {private string _Name;private int _Age;private string _Course;public Student(string Name,int Age,string Course)
        {
            _Name = Name;
            _Age = Age;
            _Course = Course;
        }public String Name
        {get{return _Name;}set{_Name = value;}
        }public int Age
        {get{return _Age;}set { _Age = value; }

        }public string Course
        {get { return _Course; }set { _Course = value; }
        }public void PrintStudentDetail()
        {
            Console.WriteLine("Name :" + _Name);
            Console.WriteLine("Age :" + _Age);
            Console.WriteLine("Course:" + _Course);
        }/* Method to Override in IComparable Interface */public int CompareTo(Object obj)
        {
            Student s = (Student)obj;return s.Name.CompareTo(_Name);
        }
}

 here i created a Class Named Student that contain its Basic properties for getting ans setting its instance variables.I have Implemented IComparable Interface by :IComparable after class name . now to make Capable our Student Type comparable we have overrided

CompareTo()  method in our class and Provided custom logic like we are sorting Our Object From Student Names .Now when we call Method Array.Sort() on our.Custom DataType Array it will sort out DataType according to Names.

lets see its Demonstration by using out created class

static void Main(string[] args)
        {
            Student[] SArray = new Student[5];
            SArray[0] = new Student("kirtan", 22, "MCA");
            SArray[1] = new Student("ghanashyam", 21, "MCA");
            SArray[2] = new Student("sanjay", 21, "MCA");
            SArray[3] = new Student("jay", 22, "BCA");
            SArray[4] = new Student("mahesh", 25, "MTech");

            Array.Sort(SArray);

            Console.WriteLine(":: Sorted by Implementing ICompatable Interface ::");
            Console.WriteLine("-------------------------------------------------");foreach (Student s in SArray)
            {
                s.PrintStudentDetail();
                Console.WriteLine("----------------------");
            }

            Console.ReadKey();

        }

 and Here is out put in which we have sorted our custom datatype using Sort() method, 

Image Loading

Sample Project Source

Download source files -26 kb

 
Sign Up to vote for this article
 
About Author
 
kirtan007
Occupation-
Company-
Member Type-Senior
Location-Not Provided
Joined date-02 Jul 2009
Home Page-http://kirtan.uni.cc
Blog Page-
He completed his Bachelor of Computer Application from Gujarat University 2009 .He is doing Master of Computer Application from Gujarat Technological University right now .. His area of Interests are Web Hacking , C# .net Windows form ,asp.net , WPF ,Silverlight ,SQL Server and Some PHP.
 
 
Other popularSectionarticles
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top