String To Value Type Converter Implementation

There are situations when one needs to convert the string values to ValueTypes(int, guid, datetime, Enums, Nullables etc.). A situation of doing these conversion could be to read Settings store in Configuration file or in database and converting them to their respective value type. I have seen people have writing if..else ladder to match the type and use the specific TypeConverter method from static class i.e. Convert.To<ValueType>();

Here’s a sample what was observed

  1. public object ConvertToValueType(string value, Type targetType)  
  2.         {  
  3.             object result = null;  
  4.   
  5.             bool isEmpty = string.IsNullOrWhiteSpace(value);  
  6.   
  7.             if (targetType == typeof (string))  
  8.             {  
  9.                 result = value;  
  10.             }  
  11.             else if (targetType == typeof (Int32) || targetType == typeof (int))  
  12.             {  
  13.                 if (isEmpty)  
  14.                 {  
  15.                     result = 0;  
  16.                 }  
  17.                 else  
  18.                 {  
  19.                     result = Int32.Parse(value);  
  20.                 }  
  21.             }  
  22.             else if (targetType == typeof (Guid))  
  23.             {  
  24.                 if (isEmpty)  
  25.                 {  
  26.                     result = Guid.Empty;  
  27.                 }  
  28.                 else  
  29.                 {  
  30.                     result = new Guid(value);  
  31.                 }  
  32.             }  
  33.             else if (targetType.IsEnum)  
  34.             {  
  35.                 result = Enum.Parse(targetType, value);  
  36.             }  
  37.             else if (targetType == typeof (byte[]))  
  38.             {  
  39.                 result = Convert.FromBase64String(value);  
  40.             }  
  41.             else if (targetType == typeof (DateTime))  
  42.             {  
  43.                 if (isEmpty)  
  44.                 {  
  45.                     result = DateTime.MinValue;  
  46.                 }  
  47.                 else  
  48.                 {  
  49.                     result = Convert.ToDateTime(value);  
  50.                 }  
  51.             }  
  52.   
  53.             return result;  
  54.         }  
This solution would work and I can easily tell many of you have seen or done things like this, but look at this again. There will be an IF…Else condition for each type in the system.

The problem can be solved by using a System class System.ComponentModel.TypeDescriptor that provide underlying information of a Type. So the above complex statement chain for Conversion can be converted to something like this using an extension method accepting generic types:

 

  1. private static bool TryConvertTo<T>(this string value, out object result)  
  2.         {  
  3.             var newType = typeof(T);  
  4.     result = default(T);  
  5.             if (string.IsNullOrWhiteSpace(value))  
  6.             {  
  7.         // simply return. A default value is already provided to out parameter.  
  8.                 return true;  
  9.             }  
  10.   
  11.             try  
  12.             {  
  13.                 var converter = TypeDescriptor.GetConverter(typeof(T));  
  14.                 result = (T)converter.ConvertFromString(value);  
  15.                 return true;  
  16.             }  
  17.             Catch(Exception exception)   
  18.             {  
  19.          // Log this exception if required.   
  20.                // throw new InvalidCastException(string.Format("Unable to cast the {0} to type {1}", value, newType, exception));  
  21.         return false;  
  22.             }  
  23.         }  

I have created this method with “Try-Parse” pattern so that it doesn’t break the application but simply returns ture/false if conversion is successful or failed due to exception or any other reasons. I found this classes in one the solution of Asp.net. You can find the complete class created for this blog post here.

Thumb Rule

Before you decide to jump into changing the business logic, try writing some tests for complete coverage of existing converter and then apply the changes and see if it’s not breaking any previously running cases. I wrote couple of tests to see if it works. You can find those tests for string to Converter here. These are not complete tests to validate every conversion, so use and test it by your own.


Similar Articles