12 August 2011

Extension - Format a version number

An interesting extension for a .NET-application is a one that formats a version object into a string that contains only the used parts of the version number; meaning:
  • 1.0.0.0 becomes 1.0,
  • 1.0.1.0 becomes 1.0.1.
Let's say I get the version of the application like so:
Version version = Assembly.GetExecutingAssembly().GetName().Version;
string formattedVersion = version.GetFormattedString();
This extension would then be the following:
public static string Format(this Version version)
{
    var result = new StringBuilder();
    result.Append(version.Major).Append('.').Append(version.Minor);

    if (version.Build > 0 || version.Revision > 0)
        result.Append('.').Append(version.Build);

    if (version.Revision > 0)
        result.Append('.').Append(version.Revision);

    return result.ToString();
}

No comments:

Post a Comment