Last active
July 28, 2016 17:40
-
-
Save davefancher/03c5b92343711cd13331c38a3b163dad to your computer and use it in GitHub Desktop.
Some helper functions for streamlining TryParse
This file contains 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
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