Reputation: 363
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?
Upvotes: 3
Views: 5356
Reputation: 29518
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.
Upvotes: 5
Reputation: 20320
Version.CompareTo(Version) returns a signed integer
negative means it's before
zero the same
positive after.
The greater the magnitude of the result the further apart the versions are.
Get rid of the switch, or condition the return of compareto first.
Upvotes: 4