Skip to content

Instantly share code, notes, and snippets.

@mivano
Created January 12, 2018 08:39
Show Gist options
  • Save mivano/d17c85b6b8a4a32b3b08cbeb72dfcb93 to your computer and use it in GitHub Desktop.
Save mivano/d17c85b6b8a4a32b3b08cbeb72dfcb93 to your computer and use it in GitHub Desktop.
StringExtensions conversions
public static class StringExtensions {
private delegate bool TryParseDelegate<T>(string s, out T result);
private static T To<T>(string value, TryParseDelegate<T> parse)
=> parse(value, out T result) ? result : default;
public static int ToInt32(this string value)
=> To<int>(value, int.TryParse);
public static DateTime ToDateTime(this string value)
=> To<DateTime>(value, DateTime.TryParse);
public static IPAddress ToIPAddress(this string value)
=> To<IPAddress>(value, IPAddress.TryParse);
public static TimeSpan ToTimeSpan(this string value)
=> To<TimeSpan>(value, TimeSpan.TryParse);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment