Compare version numbers without using split function

Sankar M picture Sankar M · Sep 27, 2011 · Viewed 64.1k times · Source

How do I compare version numbers?

For instance:

x = 1.23.56.1487.5

y = 1.24.55.487.2

Answer

JohnD picture JohnD · Sep 27, 2011

Can you use the Version class?

http://msdn.microsoft.com/en-us/library/system.version.aspx

It has an IComparable interface. Be aware this won't work with a 5-part version string like you've shown (is that really your version string?). Assuming your inputs are strings, here's a working sample with the normal .NET 4-part version string:

static class Program
{
    static void Main()
    {
        string v1 = "1.23.56.1487";
        string v2 = "1.24.55.487";

        var version1 = new Version(v1);
        var version2 = new Version(v2);

        var result = version1.CompareTo(version2);
        if (result > 0)
            Console.WriteLine("version1 is greater");
        else if (result < 0)
            Console.WriteLine("version2 is greater");
        else
            Console.WriteLine("versions are equal");
        return;

    }
}