Open In App

C# StringComparer.Compare() Method

Last Updated : 19 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In C#, the Compare method is used to compare two objects or strings and returns an indication of their relative sort order.

Example: C# program to illustrate how to use StringComparer() to perform ordinal comparison.


Output
GFG is equal to GFG

Explanation: In this example, the StringComparer.Ordinal.Compare() method checks if two strings are equal. It returns 0 when both strings are identical, a negative value if the first string is less, and a positive value if it is greater.

Overloads of StringComparer.Compare() Method

There are 2 methods in the overload list of this method:

1. Compare(Object a, Object b)

This method compares two objects and returns an indication of their relative sort order when overridden in a derived class.

Syntax:

public int Compare (object a, object b);

  • Parameters: This method takes two parameter, object a is the first object which has to be compared and the object b is the second object which has to be compared with the object a.
  • Return Type: This method returns 0, if both the objects are equal also return positive number if object a is lexicographically greater than object b, also return negative number if the object a is lexicographically lesser than the object b.

Note: This method throws an ArgumentException if the objects being compared are not of the same type.

Example: In this example, we are comparing two objects using the StringComparer.Compare(Object, Object) method.


Output
Geek is less than Geeks


2. Compare(String a, String b)

This method compares two strings and returns an indication of their relative sort order when overridden in a derived class.

Syntax:

public abstract int Compare (string a, string b);

  • Parameters: This method takes two paramter, string a is the first string which has to be compared and the string b is the second string which has to be compared with the string a.
  • Return Type: This method returns zero if both the string objects are equal, it also returns a positive number if the string a is greater than string b, it also returns a negative number if the string a is lesser than the string b.

Note: This method throws an ArgumentException

Example: In this example, we are comparing two string objects using the StringComparer.Compare(String, String) method.


Output
32

Article Tags :

Similar Reads