Consider the following line of C# code:
ProtocolVersion = new Version("6.10.7011");
So that parses the string and creates the object no problem, however it sets the Revision to -1 by default..
If I then serialise this using Newtonsoft.Json I get this:
"ProtocolVersion": {
"Major": 6,
"Minor": 10,
"Build": 7011,
"Revision": -1,
"MajorRevision": -1,
"MinorRevision": -1
}
When I later try to deserialise it, it takes issue with the negative numbers in the revisions.
‘Version’s parameters must be greater than or equal to zero. Parameter name: revision’
Revision
is read-only so I can’t just assign it or provide it in the constructor (because it doesn’t go with the string). Now I could of course append “.0” to the initial version string but I don’t know in advance how many parts it could be – could be “6” or “6.10” or “6.10.7011” – so I have to write code to detect that, which seems rather inelegant.
This is my current solution…
string versionSuffix = string.Join("", Enumerable.Repeat(".0", Math.Max(0, 3 - versionString.Count(v => v == '.'))));
ProtocolVersion = new Version($"{versionString}{versionSuffix}");
Is there a ‘correct’ way to handle this?
2
I would implement such utility method, which is more readable in my opinion:
public static Version GetCompleteVersion(string version)
{
var v = new Version(version);
var sb = new StringBuilder();
sb.Append(Math.Max(v.Major, 0));
sb.Append('.');
sb.Append(Math.Max(v.Minor, 0));
sb.Append('.');
sb.Append(Math.Max(v.Build, 0));
sb.Append('.');
sb.Append(Math.Max(v.Revision, 0));
return new Version(sb.ToString());
}