To(): a handy way to convert strings to other types

A webpage is just a giant string. As fancy that the server side abstractions can get (particularly in the .NET world) all we’re ultimately doing is reading the string given to us by the browser request so we can build the right new string for it to display to the user.

.NET is a strongly typed world so this involves lots of parsing values from the strings. We need to parse strongly typed values from query strings, server controls, configuration files and a hundred other places where .NET meets the outside world.

So since I use int.parse() so much in ASP.NET so I wrote a handy extension method called To (perfect naming thanks Dan) using generic return types and a little reflection that makes converting all these string values to another type incredibly simple:

  1. public static class StringUtils
  2. {
  3.     /// <summary>
  4.     /// This method will parse a value from a string.
  5.     /// If the string is null or not the right format to parse a valid value,
  6.     /// it will return the default value provided.
  7.     /// </summary>
  8.     public static T To<t>(this string value, T defaultValue)
  9.         where T: struct
  10.     {
  11.         var type = typeof(T);
  12.         if (value != null)
  13.         {
  14.             var parse = type.GetMethod("TryParse", new Type[] { typeof(string), type.MakeByRefType() });
  15.             var parameters = new object[] { value, default(T) };
  16.             if((bool)parse.Invoke(null, parameters))
  17.                 return (T)parameters[1];
  18.         }
  19.         return defaultValue;
  20.     }
  21.  
  22.     /// <summary>
  23.     /// This method will parse a value from a string.
  24.     /// If the string is null or not the right format to parse a valid value,
  25.     /// it will return the default value for the type.
  26.     /// </summary>
  27.     public static T To</t><t>(this string value)
  28.         where T : struct
  29.     {
  30.         return value.To</t><t>(default(T));
  31.     }
  32. }
  33. </t>

Now getting an int from the query string is only 10 extra characters to type:

  1. var value = Request.QueryString["value"].To<int>();
  2. </int>

Complete example

Posted on 23 Feb 09 by Helen Emerson (last updated on 23 Feb 09).
Filed under .NET