Skip to content

Instantly share code, notes, and snippets.

@thdotnet
Created January 31, 2018 12:16
Show Gist options
  • Save thdotnet/59d4a33ff6f7732f8c8a70d5c40b447b to your computer and use it in GitHub Desktop.
Save thdotnet/59d4a33ff6f7732f8c8a70d5c40b447b to your computer and use it in GitHub Desktop.
String Extensions
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