Last active
August 1, 2017 14:36
-
-
Save caverna/b8d7ccb8b06c2995cb22 to your computer and use it in GitHub Desktop.
General 'String 2 Value' conversion
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.ComponentModel; | |
| using System.Diagnostics; | |
| using System.Linq; | |
| [DebuggerStepThrough] | |
| public static class StringExtensions | |
| { | |
| public static T To<T>(this string text) | |
| { | |
| try { return TryTo<T>(text); } | |
| catch { return default(T); } | |
| } | |
| public static T To<T>(this string text, T @default) | |
| { | |
| try { return TryTo<T>(text); } | |
| catch { return @default; } | |
| } | |
| private static T TryTo<T>(string text) | |
| { | |
| if (string.IsNullOrEmpty(text)) | |
| throw new ArgumentOutOfRangeException(nameof(text)); | |
| if (typeof(T) == typeof(DateTime)) | |
| return (T)ToDateTime(text); | |
| if (typeof(T) == typeof(TimeSpan)) | |
| return (T)ToTimeSpan(text); | |
| if (typeof(T) == typeof(bool)) | |
| if (text.Equals("0")) | |
| text = false.ToString(); | |
| else if (text.Equals("1")) | |
| text = true.ToString(); | |
| var result = TypeDescriptor | |
| .GetConverter(typeof(T)) | |
| .ConvertFromInvariantString(text) ?? default(T); | |
| return (T)result; | |
| } | |
| private static object ToDateTime(string value) | |
| { | |
| return DateTime.Parse(value); | |
| } | |
| private static object ToTimeSpan(string value) | |
| { | |
| return TimeSpan.Parse(value); | |
| } | |
| public static T[] ToArray<T>(this string text) | |
| { | |
| try { return TryToArray<T>(text); } | |
| catch { return new T[] { }; } | |
| } | |
| private static T[] TryToArray<T>(string text) | |
| { | |
| const StringSplitOptions removeEmpty = StringSplitOptions.RemoveEmptyEntries; | |
| char[] separator = { ',' }; | |
| return text | |
| .Split(separator, removeEmpty) | |
| .Select(To<T>) | |
| .ToArray(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment