Articles → CSHARP → Basic Icomparable Example In C#

Basic Icomparable Example In C#






Objective Of This Tutorial





Prerequisites











Steps Involved




  1. Create a class which implements Icomparable interface
  2. Invoke CompareTo method in Main method








public interface IComparable<T>




int CompareTo (T com)




  1. If both the objects are equal then CompareTo method returns zero.
  2. If both the objects are not equal then CompareTo method returns a non zero value(it can be positive or negative).





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();
}




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