Strong Coders Community

Where the extreme coders hang out.
Welcome to Strong Coders Community Sign in | Join | Help Messenger
in Search

Universal data type convertor

Last post 01-31-2007, 12:31 PM by JamesCurran . 0 replies.
Sort Posts: Previous Next
  •  01-31-2007, 12:31 PM 1689
    • JamesCurran is not online. Last active: Feb 10, 2007, 10:07 AM JamesCurran
    • Top 10 Contributor
      Male
    • Joined on 11-01-2006
    • Bloomfield, NJ, USA
    • Posts 82
    • Points 1,015
    • StrongCoders

    Universal data type convertor

    Over on his blog, Mads Kristensen wrote about his Universal data type checker .  It's fairly nice, but a bit combersome to use. FOr example: CanConvert( " f637a876-9d58-4229-9559-a5e42a95fdac " , typeof (Guid)); // returns true

    We have to specify the type we want, and only get back true or false.  Now, with a bit of generics, we can simply this a bit, and make a Universal data type convertor.

    public static bool TryConvert(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 { }  // unless the CanConvertFrom was lying, this should never throw an exception.
      }

      return false;
    }

    Now, we can call it like this:  

    Guid guid;
    if (TryConvert(
    " f637a876-9d58-4229-9559-a5e42a95fdac " , guid ))
         Console.WriteLine("Good Guid {0}", guid);    
    else
         Console.WriteLine("Bad string");

     


    Truth,
    James
    • Post Points: 5
    • Alert the moderators

Powered by Community Server (Commercial Edition), by Telligent Systems