Language: C#
Generic String to Simple Type Conversion Routine
/// <summary> /// Turns a string into a typed value generically. /// Explicitly assigns common types and falls back /// on using type converters for unhandled types. /// /// Common uses: /// * UI -> to data conversions /// * Parsers /// <seealso>Class ReflectionUtils</seealso> /// </summary> /// <param name="sourceString"> /// The string to convert from /// </param> /// <param name="targetType"> /// The type to convert to /// </param> /// <param name="culture"> /// Culture used for numeric and datetime values. /// </param> /// <returns>object. Throws exception if it cannot be converted.</returns> public static object StringToTypedValue(string sourceString, Type targetType, CultureInfo culture) { object Result = null; bool isEmpty = false; if (sourceString == null || sourceString == string.Empty) isEmpty = true; if (targetType == typeof(string)) Result = sourceString; else if (targetType == typeof(Int32) || targetType == typeof(int)) { if (isEmpty) Result = 0; else Result = Int32.Parse(sourceString, NumberStyles.Any, culture.NumberFormat); } else if (targetType == typeof(Int64)) { if (isEmpty) Result = (Int64)0; else Result = Int64.Parse(sourceString, NumberStyles.Any, culture.NumberFormat); } else if (targetType == typeof(Int16)) { if (isEmpty) Result = (Int16)0; else Result = Int16.Parse(sourceString, NumberStyles.Any, culture.NumberFormat); } else if (targetType == typeof(decimal)) { if (isEmpty) Result = 0M; else Result = decimal.Parse(sourceString, NumberStyles.Any, culture.NumberFormat); } else if (targetType == typeof(DateTime)) { if (isEmpty) Result = DateTime.MinValue; else Result = Convert.ToDateTime(sourceString, culture.DateTimeFormat); } else if (targetType == typeof(byte)) { if (isEmpty) Result = 0; else Result = Convert.ToByte(sourceString); } else if (targetType == typeof(double)) { if (isEmpty) Result = 0F; else Result = Double.Parse(sourceString, NumberStyles.Any, culture.NumberFormat); } else if (targetType == typeof(Single)) { if (isEmpty) Result = 0F; else Result = Single.Parse(sourceString, NumberStyles.Any, culture.NumberFormat); } else if (targetType == typeof(bool)) { if (!isEmpty && sourceString.ToLower() == "true" || sourceString.ToLower() == "on" || sourceString == "1") Result = true; else Result = false; } else if (targetType.IsEnum) Result = Enum.Parse(targetType, sourceString); else if (targetType == typeof(byte[])) { // TODO: Convert HexBinary string to byte array Result = null; } // Handle nullables explicitly since type converter won't handle conversions // properly for things like decimal separators currency formats etc. // Grab underlying type and pass value to that else if (targetType.Name.StartsWith("Nullable`")) { if (sourceString.ToLower() == "null") Result = null; else { targetType = Nullable.GetUnderlyingType(targetType); Result = StringToTypedValue(sourceString, targetType); } } else { TypeConverter converter = TypeDescriptor.GetConverter(targetType); if (converter != null && converter.CanConvertFrom(typeof(string))) Result = converter.ConvertFromString(null, culture, sourceString); else { Debug.Assert(false, "Type Conversion not handled in StringToTypedValue for " + targetType.Name + " " + sourceString); throw (new InvalidCastException(Resources.StringToTypedValueValueTypeConversionFailed + targetType.Name)); } } return Result; } /// <summary> /// Turns a string into a typed value generically. /// Explicitly assigns common types and falls back /// on using type converters for unhandled types. /// /// Common uses: /// * UI -> to data conversions /// * Parsers /// <seealso>Class ReflectionUtils</seealso> /// </summary> /// <param name="sourceString"> /// The string to convert from /// </param> /// <param name="targetType"> /// The type to convert to /// </param> /// <returns>object. Throws exception if it cannot be converted.</returns> public static object StringToTypedValue(string sourceString, Type targetType) { return StringToTypedValue(sourceString, targetType, CultureInfo.CurrentCulture); } /// <summary> /// Generic version allow for automatic type conversion without the explicit type /// parameter /// </summary> /// <typeparam name="T">Type to be converted to</typeparam> /// <param name="sourceString">input string value to be converted</param> /// <param name="culture">Culture applied to conversion</param> /// <returns></returns> public static T StringToTypedValue<T>(string sourceString, CultureInfo culture) { return (T) StringToTypedValue(sourceString, typeof(T), culture); } /// <summary> /// Generic version allow for automatic type conversion without the explicit type /// parameter. Defaults conversion to CurrentCulture. /// </summary> /// <typeparam name="T">Type to be converted to</typeparam> /// <param name="sourceString">input string value to be converted</param> /// <returns></returns> public static T StringToTypedValue<T>(string sourceString) { return (T)StringToTypedValue(sourceString, typeof(T), CultureInfo.Current); }
Tags:
Comment:
Converts a string value to a specific type. Useful for various generic framework routines and UI routines that need to update object properties.
Report Abuse
Subscribe
Discuss
What's new
What is it
New Snippet
Recent Snippets
My Snippets
Web Code
Search

