Articles → .NET → Basic IComparable example in C#
Basic IComparable example in C#
Objective of this Tutorial
Prerequisites
Steps Involved
public interface IComparable<T>
Step 1: Create a class which 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;
}
}
Step 2: 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();
}
Click to Enlarge