Simon
Simon

Reputation: 4844

What is the best way to parse a single part of a version number into a Version type

Context: I want to parse a single part as string into a Version type:

string lVersionAsString = "6";

Problem: Parsing a Version number with only a single part results in an Exception:

Version lVersion = new Version(lVersionAsString); // Exception

Reason: The Version class requires minimum two version parts. E.g. the value 6.1

So I tried the following simple solution:

var lVersionParts = lVersionAsString.Split('.');

if (lVersionParts.Length == 1)
{
    lVersionAsString += ".0";
}

Version lVersion = new Version(lVersionAsString); // Works

Is there any better way?

Upvotes: 0

Views: 526

Answers (3)

MatSnow
MatSnow

Reputation: 7537

You could write this in one line like this.

Version lVersion = new Version(lVersionAsString.PadRight(lVersionAsString.Length + lVersionAsString.IndexOf(".") * -1, ".").PadRight(lVersionAsString.Length + lVersionAsString.IndexOf(".") * -1 + 1, "0"));

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460350

You could use Version.TryParse:

Version lVersion;
if (!Version.TryParse(lVersionAsString, out lVersion)) 
    lVersion = new Version(lVersionAsString += ".0");

Presuming that the string has a valid version most times, it's better to parse him directly and only use the fallback approach otherwise. You could also use TryParse then if you want to be sure.


Corak posted an interesting comment:

Another edge case: what if lVersionAsString was "6.5.4.3.2"?

Here is an approach that handles both cases, it truncates the "mini"-version(s):

Version lVersion;
while (!Version.TryParse(lVersionAsString, out lVersion) && lVersionAsString.Length > 0)
{
    string[] versionTokens = lVersionAsString.Split('.');
    if (versionTokens.Length == 1 && !versionTokens[0].All(char.IsDigit)) break; // needed with soemthing like "Foo" as version
    lVersionAsString = versionTokens.Length == 1 
        ? lVersionAsString += ".0" 
        : lVersionAsString.Remove(lVersionAsString.LastIndexOf('.'));
}

Upvotes: 4

Mong Zhu
Mong Zhu

Reputation: 23732

you could simply check whether the number is in the dot format:

if(!lVersionAsString.Contains("."))
{
    lVersionAsString += ".0";
}

Upvotes: 6

Related Questions