Articles → CSHARP → Basic Icomparable Example In C#

Basic Icomparable Example In C#






Purpose





Create A Class That Implements Icomparable Interface




public class Person : IComparable<Person>
{
   public Person()
   { }
   
   public Person(string PersonName, int Age, string Address)
   {
      this.PersonName = PersonName;
      this.Age = Age;
      this.Address = Address;
   }

   public int CompareTo(Person other)
   {
      bool isEqual = true;

      if (this.PersonName.CompareTo(other.PersonName) != 0)
          isEqual = false;

      if (this.Age != other.Age)
          isEqual = false;

      if (this.Address.CompareTo(other.Address) != 0)
          isEqual = false;

      return isEqual == true ? 1 : 0;
   }

   public string PersonName { get; set; }
   public int Age { get; set; }
   public string Address { get; set; }
}



Invoke CompareTo Method In Main Method


static void Main(string[] args)
{
  Person p1 = new Person("Karan Gupta",32,"Gurgaon");
  Person p2 = new Person("Karan Gupta", 32, "Gurgaon");

  Console.WriteLine(p1.CompareTo(p2));
  Console.WriteLine(Environment.NewLine);

  Person p3 = new Person("Karan Gupta", 32, "Gurgaon");
  Person p4 = new Person("Karan Gupta", 32, "Delhi");

  Console.WriteLine(p3.CompareTo(p4));
  Console.ReadLine();
}



Output


Picture showing the output of the IComparable interface in C#
Click to Enlarge


Posted By  -  Karan Gupta
 
Posted On  -  Thursday, March 6, 2014

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250