Int32.CompareTo Method in C# with Examples

CsharpServer Side ProgrammingProgramming

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
raja
Published on 11-Nov-2019 06:54:13
Advertisements