vote buttons
1
11 Feb 2015 by Charlie

Generic Function to Convert a String to any Type

Contract
GlobalExtensionMethods
public static T ConvertTo<T>(this string str); public static bool TryConvertTo<T>(this string str, out T converted);
Test Cases
vote buttons
0
public void ConvertStringToInt() { Assert.AreEqual(123, "123".ConvertTo<int>()); }
vote buttons
0
public void ConvertStringToDecimal() { Assert.AreEqual(123.456, "123.456".ConvertTo<double>(), 0.0001); }
vote buttons
0
public void ConvertStringToDateTime() { Assert.AreEqual(new DateTime(2015,2,12), "12-Feb-2015".ConvertTo<DateTime>()); }
vote buttons
0
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

1 Solution

vote buttons
1
0.17
avg time in ms
.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; } }
You must have at least 2 reputation points to edit this solution
Test Case Run Summary
ConvertStringToInt
ConvertStringToDecimal
ConvertStringToDateTime
ConvertStringToBoolean
download solution
Try this Solution
Comments