C# String Compare Method

In c#, the string Compare method is used to compare a two specified strings and return an integer value that indicates their relative position in the sort order.


Here, the return integer value indicates the lexical relationship between the two specified strings. Following table lists the values which will be return by the Compare method after comparing the two specified strings.


strA == strB 0
strA > strB 1
strA < strB -1

Following is the pictorial representation of comparing a two strings using Compare() method in c# programming language.


C# String Compare Method Representation Diagram


If you observe above diagram, we are comparing two strings ”Suresh” and “Dasari” by using Compare method and return an integer value “1”.

C# String Compare Method Syntax

Following is the syntax of defining a Compare method to compare a two specified strings in c# programming language.


public int Compare(string string1, string string2)

If you observe syntax, the Compare method will compare a given two strings and return an integer value.

C# String Compare Method Example

Following is the example of using Compare() method to compare a given two strings and return an integer value in c# programming language.


using System;


namespace Tutlane


    class Program


        static void Main(string[] args)


            string str1 = "Suresh";

            string str2 = "Dasari";

            Console.WriteLine("Comparison of {0} and {1} Result: {2}", str1, str2, string.Compare(str1, str2));


            string str3 = "Rohini";

            string str4 = "Trishika";

            Console.WriteLine("Comparison of {0} and {1} Result: {2}", str3, str4, string.Compare(str3, str4));


            Console.WriteLine("\nPress Enter Key to Exit..");





If you observe above example, we used a Compare() method to compare a two given strings and return an integer value.


When we execute above c# program, we will get the result like as shown below.


C# String Compare Method Example Result


This is how we can use Compare() method to compare two given strings and return an integer value which indicates a lexical relationship between two strings in c# programming language. 

Topics Covered