- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Int32.CompareTo Method in C# with Examples
The Int32.CompareTo method in C# is used to compare this instance to a specified object or Int32 and returns an indication of their relative values.
Syntax
Following is the syntax −
public int CompareTo (int val); public int CompareTo (object val);
Above, the value of the 1st syntax is an integer to compare, whereas, in the 2nd syntax, it is an object to compare.
The return value is less than zero if the current instance is less than the value. It’s zero, if the current instance is equal to value, whereas return value is more than zero if the current instance is more than value.
Example
Let us now see an example to implement the Int32.CompareTo method −
using System; public class Demo { public static void Main(){ int val1 = 20; int val2 = 18; Console.WriteLine("Value 1 = "+val1); Console.WriteLine("Value 2 = "+val2); Console.WriteLine("Return value (comparison) = "+val1.CompareTo(val2)); } }
Output
This will produce the following output −
Value 1 = 20 Value 2 = 18 Return value (comparison) = 1
Example
Let us now see another example to implement the Int32.CompareTo method −
using System; public class Demo { public static void Main(){ int val1 = 50; int val2 = 50; Console.WriteLine("Value 1 = "+val1); Console.WriteLine("Value 2 = "+val2); Console.WriteLine("Return value (comparison) = "+val1.CompareTo(val2)); } }
Output
This will produce the following output −
Value 1 = 50 Value 2 = 50 Return value (comparison) = 0
Advertisements