Universal data type checker

by Mads Kristensen 30. January 2007 17:54

In many different scenarios we need to check if a string can be converted into an integer e.g. This could be when we work with query strings and need to check if they match a certain data type. In VB.NET you can use the IsNumeric and IsDate functions, but that's about it. You are left to your own data type checking logic the rest of the time. It would be cool if we could have a method that could check all data types that is represented by strings such as integers, guids, booleans etc.

Here is a method that does just that. It can check all the string based types and also enums.

   
/// <summary> /// Checks the specified value to see if it can be /// converted into the specified type. /// <remarks> /// The method supports all the primitive types of the CLR /// such as int, boolean, double, guid etc. as well as other /// simple types like Color and Unit and custom enum types. /// </remarks> /// </summary> /// <param name="value">The value to check.</param> /// <param name="type">The type that the value will be checked against.</param> /// <returns>True if the value can convert to the given type, otherwise false.</returns> public static bool CanConvert(string value, Type type) { if (string.IsNullOrEmpty(value) || type == null) return false; System.ComponentModel.TypeConverter conv = System.ComponentModel.TypeDescriptor.GetConverter(type); if (conv.CanConvertFrom(typeof(string))) { try { conv.ConvertFrom(value); return true; } catch { } } return false; }

Example of use

Let's try some different examples

   
CanConvert("12", typeof(int)); // returns true CanConvert("f637a876-9d58-4229-9559-a5e42a95fdac ", typeof(Guid)); // returns true CanConvert("Backspace", typeof(System.ConsoleKey)); // returns true CanConvert("10px", typeof(System.Web.UI.WebControls.Unit)); // returns true CanConvert("red", typeof(System.Drawing.Color)); // returns true
* Only $4.95/month ASP.NET & Windows 2008 + IIS 7 Hosting! FREE SQL Included

Tags:

Server-side

Comments

1/30/2007 6:50:02 PM #

Francesco

I always learn something from your posts. Thanks very much for sharing your knowledge

Francesco |

1/31/2007 7:14:46 AM #

 Eber Irigoyen

the RSS (in google reader) is reeeeeeaaally messed up (the code)

Eber Irigoyen |

1/31/2007 11:29:59 PM #

 Damien Guard

The problem with this is that typically after the test you will then perform the conversion.  This method means you end up doing every conversion twice - once for the test and once for real.  This can be a real performance problem with strings which is why .NET 2.0 includes the TryParse methods.

Int32 result;
if (Int32.TryParse("12", out result)) {
  // Go do something with result
}

[)amien

Damien Guard |

2/1/2007 1:42:44 AM #

 James Curran

Of course, with generics, we can simplify the method call, and incorporate the actual conversion:
public static bool TryConvert < T >(string value, out T t)
{
  t= default(T);
  if (string.IsNullOrEmpty(value))
    return false;

  System.ComponentModel.TypeConverter conv = System.ComponentModel.TypeDescriptor.GetConverter(typeof(T));
  if (conv.CanConvertFrom(typeof(string)))
  {
    try
    {
      t = (T) conv.ConvertFrom(value);
      return true;
    }
    catch
    {
  }
  }

  return false;
}

/*   Called like
       int a;
       if (CanConvert("123", out a))
*/

In fact, you can extend it to any two types:
public static bool TryConvert < T, U > (U value, out T t) where U:class
{
    t= default(T);
  if (value == null)
      return false;

  System.ComponentModel.TypeConverter conv = System.ComponentModel.TypeDescriptor.GetConverter(typeof(T));
  if (conv.CanConvertFrom(typeof(U)))
  {
    try
    {
      t = (T) conv.ConvertFrom(value);
      return true;
    }
    catch { }
  }
  return false;
}
(note this is limited to converting a reference type to any type.  To convert any type to any type, remove the where clause, and the "if (value == null)" clause.  Also, note the just because you think something can be convertable, doesn't mean that the CLR does.  A double cannot be converted to an int, for example.

James Curran |

Comments are closed

About the slave

Mads Kristensen Mads Kristensen
Web developer at ZYB and founder of BlogEngine.NET. More...

LinkedIn ZYB Facebook Last.fm Twitter View Mads Kristensen's profile on Technorati

The Lounge

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2008