Tuesday, August 4, 2015

Converting Data Types

A few years ago I came across a snippet of code that I immediately added to my arsenal.  Ask any developer and they will tell you that casting data from one type to another can sometimes be tricky and cause unwanted behavior.  That task becomes even more difficult when you throw in a database of some sort since not all databases support all data types.  With this in mind, this snippet of code has been in nearly every project I have worked on since.  While this snippet may not be new to all of you, I hope that it is to some.

    public static class Helpers
    {
        public static T TryConvertTo( this object value)
        {
            try
            {
                if (( typeof(T)) == typeof( Guid))
                {
                    return (T)Convert.ChangeType(value.ToString().TryConvertToGuid(), typeof(T));
                } //end if

                return (T) Convert.ChangeType(value, typeof(T));
            } //end try
            catch ( Exception ex)
            {
                return default(T);
            } //end catch
        } //end TryConverTo<>

        public static Guid TryConvertToGuid( this object value)
        {
            try
            {
                return new Guid(value.ToString());
            } //end try
            catch ( Exception ex)
            {
                return default( Guid);
            } //end catch
        } //end TryConverToGuid
    } //end class    

Taking a look at the code above we see a static class that I call helpers, although the name of the class is not important.  The first class is called TryConvertTo and takes a type T and attempts to convert it into the type you pass.  Upon failure it returns the default of that type.  For instance, if I use the following code:

    var someString = "I am a string";

    someString = someString.TryConvertTo<int>();

I would get back a 0 since I am attempting to convert a string to an int which cannot be done in this case.  I get a zero because the TryConvertTo will try to convert the string to an int, it will fail and thus fall into the catch where the default of T, int, will be returned instead.

The second function is a try convert to Guid which gets called automatically when you attempt to convert to a Guid.  Same concept applies here, however a different route is taken when converting Guids.  Upon failure it will return a Guid of all 0's which can easily be detected by the calling code.

I hope you find this little snippet as useful as I do.  Again, I am not the author of this snippet, I was unable to track down who was, however it is definitely worth sharing.  I am happy to give credit if you want to reach out to me and show you are the original author.