|
11 Feb 2015 by Charlie
Generic Function to Convert a String to any TypeContract
GlobalExtensionMethods
public static T ConvertTo<T>(this string str);
public static bool TryConvertTo<T>(this string str, out T converted);
Test Cases
ConvertStringToInt
public void ConvertStringToInt()
{
Assert.AreEqual(123, "123".ConvertTo<int>());
}
ConvertStringToDecimal
public void ConvertStringToDecimal()
{
Assert.AreEqual(123.456, "123.456".ConvertTo<double>(), 0.0001);
}
ConvertStringToDateTime
public void ConvertStringToDateTime()
{
Assert.AreEqual(new DateTime(2015,2,12), "12-Feb-2015".ConvertTo<DateTime>());
}
ConvertStringToBoolean
public void ConvertStringToBoolean()
{
Assert.AreEqual(false, "False".ConvertTo<bool>());
Assert.AreEqual(false, "false".ConvertTo<bool>());
Assert.AreEqual(true, "true".ConvertTo<bool>());
Assert.AreEqual(true, "True".ConvertTo<bool>());
Assert.AreEqual(false, "FALSE".ConvertTo<bool>());
Assert.AreEqual(true, "TRUE".ConvertTo<bool>());
}
You must have at least 2 reputation points to edit the problem definition
|
|
.NET BCL already provides converters for basic types. The converter instance can be obtained from System.ComponentModel.TypeDescriptor.GetConverter function. If support for other types is required you have to write TypeConverter for that type. More details on msdn.
using System.ComponentModel;
public static class GlobalExtensionMethods
{
public static bool TryConvertTo<T>(this string str, out T result)
{
result = default(T);
var converter = TypeDescriptor.GetConverter(typeof(T));
if(!converter.CanConvertFrom(typeof(string))) return false;
result = (T)(converter.ConvertFromInvariantString(str));
return true;
}
public static T ConvertTo<T>(this string str)
{
T result;
if(!str.TryConvertTo<T>(out result))
throw new InvalidOperationException(
String.Format("No type conversion exist from string to {0}", typeof(T)));
return result;
}
}
|
|||
|
||||
|
Test Case Run Summary
ConvertStringToInt
ConvertStringToDecimal
ConvertStringToDateTime
ConvertStringToBoolean
|
||||
| download solution | ||||
| Try this Solution | ||||
|
Comments
|