C#: Compare Application Version Numbers

UPDATE: As discussed in the comments, 99% of the time using the System.Version class included in the .net Framework will suffice for comparing application version numbers. Documentation for this can be found here. The below post will help you if for some reason (ex. you use commas instead of periods to separate the version number) the System.Version class will not work

When incorporating an automatic update feature into an application, one of the things that you will need to do is compare the installed version number to the currently available version number. Given version numbers of the format ‘X.X.X.X’ I have seen some people suggest simply removing the periods, converting the string to an integer and doing a simple comparison of the integers. Such a solution works great if you have complete control over the format of the version number and you can ensure the number of digits per grouping stays the same. But, suppose you have the following two version numbers: 1.4.0 and 1.1.28. Following the logic explained above, you will be comparing the integers 140 and 1128 and the second version will be determined to be greater than the first, which is incorrect.

In order to alleviate this problem, I have created the following method below to correctly compare two version numbers. This method uses the SplitToList extension which takes a string, splits it based on a given string and then converts each element to the specified type. You can find a more detailed explanation and the code here.

public static int CompareVersionNumbers(string versionA, string versionB)
    // Convert each version numbers string to a list of integers
    List<int> a = versionA.SplitToList<int>(".");
    List<int> b = versionB.SplitToList<int>(".");            
    // Ensure that each of the lists are the same length
    while(a.Count < b.Count) { a.Add(0); }
    while(b.Count < a.Count) { b.Add(0); }

    // Compare elements of each list
    for (int i = 0; i < a.Count; i++)
        // If the element from list A is greater than B, 
        // versionA is greater than versionB and visa versa.
        // If they are equal, go to the next element.
        if (a[i] > b[i])
            return 1;
        else if (b[i] > a[i])
            return -1;

    // If we reach this point, the versions are equal
    return 0;