Skip to content

Instantly share code, notes, and snippets.

@davefancher
Last active July 28, 2016 17:40
Show Gist options
  • Save davefancher/03c5b92343711cd13331c38a3b163dad to your computer and use it in GitHub Desktop.
Save davefancher/03c5b92343711cd13331c38a3b163dad to your computer and use it in GitHub Desktop.
Some helper functions for streamlining TryParse
public delegate bool Parser<T>(string s, out T result);
public class ParseResult<T>
{
internal ParseResult(bool success, T value)
{
Success = success;
Value = value;
}
public bool Success { get; }
public T Value { get; }
}
public static class ParseHelper
{
public static Func<string, ParseResult<T>> TryParse<T>(Parser<T> parser) =>
s =>
{
T result;
var success = parser(s, out result);
return new ParseResult<T>(success, result);
};
public static Func<string, ParseResult<int>> TryParseInt32 => TryParse<int>(int.TryParse);
public static Func<string, ParseResult<DateTime>> TryParseDateTime => TryParse<DateTime>(DateTime.TryParse);
public static Func<string, ParseResult<double>> TryParseDouble => TryParse<double>(double.TryParse);
// ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment