Created
July 18, 2012 03:38
-
-
Save badmotorfinger/3134006 to your computer and use it in GitHub Desktop.
Generic function to cast a string value to another value using .NET's built in TryParse methods.
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
// Usage | |
var intResult = Parse("1", 0, int.TryParse); // Returns 1 | |
var dateResult = Parse("asdf", DateTime.Now, DateTime.TryParse); // Returns 18/07/2012 1:39:06 PM | |
delegate TParsedValue ParseFunc<T, U, TParsedValue>(T input, out U output); | |
static V Parse<T, V>(T valueToBeParsed, V defaultVal, ParseFunc<T, V, bool> dele) { | |
V result; | |
bool success = dele(valueToBeParsed, out result); | |
if (success) { | |
return result; | |
} | |
return defaultVal; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment