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