Click here to Skip to main content

Eligible Contests

Tagged as

Introduction

Recently doing some design and coding around "version" information, I found the System.Version class quite strict in its parse mechanics. One of the constructor overrides takes a "version" string. There's also a static Parse and even a TryParse method, but all three of these require a string with "major", "minor", and "version" components (delimited with a '.'). Quite unforgiving and in the past, I've always found Microsoft C# to be flexible - but not in this case.

Background

I am not a huge fan of extensions but do find cases arise occasionally where they are a good fit for solving certain problems. For example, with an "int" extension, one can create a static method that can determine a value lies between a range of two values, such as 5.Between(4,6). I decided to use an extension to solve my problem with the System.Version class.

Using the Code

Here's my solution:

public static class StringExtensions
{
    private const char KDelimiter = '.';

    //// <summary>
    //// Parse
    ////
    //// System.Version.TryParse (and therefore the constructor that takes a string) fails with
    //// an exception if the version string is not formatted correctly.  We need a more forgiving
    //// Parse that takes strings like "12" and "12.2"
    //// </summary>
    //// <param name="raw"></param>
    //// <returns></returns>
    public static Version ToVersion(this string raw)
    {
        int major = 0, minor = 0, build = 0;

        string[] tokens = raw.Split(KDelimiter);

        if (tokens.Length > 0)
        {
            int.TryParse(tokens[0], out major);

            if (tokens.Length > 1)
            {
                int.TryParse(tokens[1], out minor);

                if (tokens.Length > 2)
                {
                    int.TryParse(tokens[2], out build);
                }
            }
        }

        return new Version(major, minor, build);
    }
}

Including the namespace from the above code will make this extension available and you'll be able to get a System.Version like this:

var version = "12.5".ToVersion();

or:

string raw = "12";
var version = raw.ToVersion();

Points of Interest

Hope this tip spurs you to learning more about C# and you find extensions fun and useful!

History

This is the initial revision of code for using a C# extension to solve a simple problem.

License