C# .Compare()
The .Compare() method is a string method that compares the alphabetical order of two specified strings and returns an integer that represents their relative ranking.
Syntax
String.Compare(string1, string2, ignoreCase);
- The
.Compare()method is called on theStringclass. It takes twostringtype arguments,string1andstring2, and compares them alphabetically. ignoreCaseis an optionalbooleantype argument. By default the.Compare()method is case-sensitive. Passingtrueas the third argument makes the.Compare()method case-insensitive.
The .Compare() method returns an integer that represents the relative order of string1 and string2 in the alphabet:
-1ifstring1comes beforestring20if their position is the same (string1andstring2are identical)1ifstring2comes beforestring1
Example
In the following example, the .Compare() method compares "Pizza" with "pizza" and "waffle". Then the .WriteLine() method prints the returned integer to the console:
using System;public class Example {public static void Main (string[] args) {string str1 = "Pizza", str2 = "pizza", str3 = "waffle";Console.WriteLine(String.Compare(str1, str2));Console.WriteLine(String.Compare(str1, str3));}}
In the first case, "pizza" comes before "Pizza" in alphabetical order, as it is lowercase and the method is case-sensitive. In the second case, "Pizza" comes before "waffle" in alphabetical order. This example results in the following output:
1-1
Codebyte Example
In the following runnable example, the .Compare() method determines the alphabetical order of string1 and string2, while the letter casing is ignored. Finally, the .WriteLine() method prints the returned integer to the console.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C# on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn Microsoft's popular C# programming language, used to make websites, mobile apps, video games, VR, and more.
- Beginner Friendly.15 hours