Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Version object is comparing two versions incorrectly

I am using the Version object in order to run a CompareTo against two version numbers and making X happen if the version is >= versionA.

My issue is that in the below code, the CompareTo is declaring that VersionB is greater than VersionA.

Version versionA = new Version("2.12");
Version versionB = new Version("2.121");

switch (versionB.CompareTo(versionA))
                {
                    case 0: // Equal To
                        _doThis = true;
                        break;
                    case 1: // Greater Than
                        _doThat = true;
                        break;
                    case 2: // Less Than
                        _doNothing = true;
                        break;
                }

This comparison hits case 2. I am using a regex to match a firmware version being passed to the method, as you see here:

^\S+\s(?(\d+.*)+)\s*.*$

I will accept something along the lines of "Version 2.12" and this regex will leave me with just "2.12", which then gets initialized into a Version object.

Anyone have any ideas on why .NET is telling me that Version 2.12 is a newer Version than 2.121?


EDIT:

I have altered my code to be as follows:

Version versionA = new Version("2.12");
Version versionB = new Version("2.121");

if (versionB.CompareTo(versionA) >= 0)
{
     _doThis = true;
}

And it works correctly. Now though, if I compare "2.11" to "2.121", it also returns 1. Shouldn't this comparison return a -1?

like image 342
Chris Bohatka Avatar asked Sep 02 '26 16:09

Chris Bohatka


1 Answers

The Version class provides operator overloads for the comparison operators, why not use those? It really makes the intent of the code clearer.

Meaning you can simply write:

if(versionB >= versionA) {
  _doThis = true;
}

To me, that is much clearer than calling CompareTo and inspecting the sign of the return value.

like image 94
MarkPflug Avatar answered Sep 05 '26 05:09

MarkPflug