Had a need to write a re-usable function at work to compare version numbers so that an action could be taken accordingly. It’s pretty simple but thought I’d share it anyway.
What I’m doing here is accepting two versions. This function will tell you, in the end, if ver1 is greater than, equal to, or less than ver2. First I split each one using the “.” and store the array. I do this because, obviously, a number with multiple “.’s” isn’t really a number so you have to break them up and compare them separately.
Next I decide which one is the longer version number, for example 8.0.7601.3572 vs 8.1.7601. The second one has the least amount of subversions so I would only compare the first 3 version numbers instead of 4. Why? Well, to be honest, if you are using this function you’re 99% of the time going to be comparing versions of the same software and the number of subversions will probably be the same. I know this wont be true 100% of the time but lets go with it. In the event that the first 3 subversions are equal but one has an addition .### will you really know whether it’s greater, equal, or less than the other version had it been showing a subversion? Who knows. It would be simple enough to take this into consideration but I didn’t need to.
Next is just a for loop using a counter that counts up to the lowest number of subversions and uses that counter as the index to the array that holds the subversions for each version. It compares them using the built-in .CompareTo() method for [ints] and you can see in the switch what value that method returns depending on the result. I break out of the loop unless they are equal because there is no need to compare further once you already hit a value that is greater or equal. Using the numbers above this function would compare the first “8’s” and see they are equal, the move onto the next one which is 0 for ver1 and 1 for ver2. The loop would see ver2 is greater and then not bother to continue comparing the 7601 to 7601 because there is no need.
Once you return that value you can easily use it to act upon, such as we did below:
And there you have it…