System.Version.CompareTo Method

Compares the current Version object to a specified object and returns an indication of their relative values.

Syntax

public int CompareTo (object version)

Parameters

version
An object to compare, or null.

Returns

A signed integer that indicates the relative values of the two objects, as shown in the following table.

Less than zero

The current Version object is a version before version.

Zero

The current Version object is the same version as version.

Greater than zero

The current Version object is a version subsequent to version.

-or-

version is null.

Exceptions

TypeReason
ArgumentException version is not a Version and is not a null reference

Remarks

The components of Version in decreasing order of importance are: major, minor, build, and revision. An unknown component is assumed to be older than any known component.

For example:

  • Version 1.1 is older than version 1.1.0

  • Version 1.1 is older than version 1.1.1

  • Version 1.1 is older than version 1.1.2.3

  • Version 1.1.2 is older than version 1.1.2.4

  • Version 1.2.5 is newer than version 1.2.3.4

Example

C# Example

using System;
class VersionTest {
   static string Test ( Version v1, Version v2 ) {
      int i = v1.CompareTo(v2);
      if ( i < 0 )
         return "older than";
      else if ( i == 0 )
         return "the same as";
      else
         return "newer than";
   }
   public static void Main() {
      Version vers1 = new Version( "6.1.2.4" );
      Version vers2 = new Version( 6, 1 );
      Version vers3 = new Version( 6, 1, 3 );
      Console.Write("Version {0} is {1} ",
                    vers1, Test(vers1, vers2));
      Console.WriteLine("version {0}", vers2); 
      Console.Write("Version {0} is {1} ",
                    vers1, Test(vers1, vers3));
      Console.WriteLine("version {0}", vers3); 
      Console.Write("Version {0} is {1} ",
                    vers3, Test(vers3, vers3));
      Console.WriteLine("version {0}", vers3); 
      Console.Write("Version {0} is {1} ",
                    vers2, Test(vers2, vers1));
      Console.WriteLine("version {0}", vers1);
   }
}
   

The output is

Version 6.1.2.4 is newer than version 6.1
Version 6.1.2.4 is older than version 6.1.3
Version 6.1.3 is the same as version 6.1.3
Version 6.1 is older than version 6.1.2.4

Requirements

Namespace: System
Assembly: mscorlib (in mscorlib.dll)
Assembly Versions: 1.0.5000.0, 2.0.0.0, 4.0.0.0