|
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
Created By Rahul
public void ConvertStringToInt()
{
Assert.AreEqual(123, "123".ConvertTo<int>());
}
ConvertStringToDecimal
Created By Rahul
public void ConvertStringToDecimal()
{
Assert.AreEqual(123.456, "123.456".ConvertTo<double>(), 0.0001);
}
ConvertStringToDateTime
Created By Rahul
public void ConvertStringToDateTime()
{
Assert.AreEqual(new DateTime(2015,2,12), "12-Feb-2015".ConvertTo<DateTime>());
}
ConvertStringToBoolean
Created By Rahul
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 be logged in to add test cases
|
|
11 Feb 2015 by Charlie
.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
|