Skip to content

Instantly share code, notes, and snippets.

@badmotorfinger
Created July 18, 2012 03:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save badmotorfinger/3134006 to your computer and use it in GitHub Desktop.
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.
// 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