Int16.CompareTo() Method in C#


The Int16.CompareTo() method in C# is used to compare this instance to a specified object or another Int16 instance and returns an integer that indicates whether the value of this instance is less than, equal to, or greater than the value of the specified object or the other Int16 instance.

Syntax

Following is the syntax −

public int CompareTo (short val);
public int CompareTo (object val);

Above, in the 1st syntax, the value val is an integer to compare, whereas Val in the 2nd syntax 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 Int16.CompareTo() method −

using System;
public class Demo {
   public static void Main(){
      short val1 = 20;
      short 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) = 2

Example

Let us now see another example to implement the Int16.CompareTo() method −

using System;
public class Demo {
   public static void Main(){
      short val1 = 10;
      short val2 = 10;
      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 = 10
Value 2 = 10
Return value (comparison) = 0

Updated on: 12-Nov-2019

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements