TryConvertTo<T> C# Helper


Overview

This snippet of code has been in my arsenol for many years. I am not sure where I first learned it or heard of it, but it finds its way into nearly all of my projects. Using Generic types it allows for quick and accurate conversions from any data-type to any other data-type. If the conversion cannot happen the default of the targeted data-type is returned.

I find this snippet most useful when scrubbing user data or ensuring data from an external data-source is valid. This works with any primitive data-type and can save you many hours of troubleshooting if used to scrub data.

Code

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

Usage

Since this is a static class you can call it on any data-type like below:

string to int:
"123".TryConvertTo<int>()
Returns
123 type casted to an int
string to int:
"abc123".TryConvertTo<int>()
Returns
0 type casted to an int since abc123 cannot be successfully converted
Variable to T
var someIntAsString = "123";

int intAsInt = someIntAsString.TryConvertTo<int>();
Returns
123 type casted as an int