Skip to content

Instantly share code, notes, and snippets.

@dahlbyk
Last active January 14, 2018 06:05
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 dahlbyk/879adfe5cd6b19604fae71229208833a to your computer and use it in GitHub Desktop.
Save dahlbyk/879adfe5cd6b19604fae71229208833a to your computer and use it in GitHub Desktop.
static class Original
{
// Adding new extensions is simple copy/paste
public static Int32? ConvertToInt32(this string value)
{
return Int32.TryParse(value, out var result) ? result : (Int32?)null;
}
public static Int64? ConvertToInt64(this string value)
{
return Int64.TryParse(value, out var result) ? result : (Int64?)null;
}
}
static class Refactored
{
// This isn't simple
delegate bool TryParser<T>(string s, out T value);
static T? Convert<T>(this string value, TryParser<T> parser) where T : struct
{
return parser(value, out T result) ? result : (T?)null;
}
// But adding new extensions is simpler copy/paste
public static Int32? ConvertToInt32(this string value)
{
return value.Convert<Int32>(Int32.TryParse);
}
public static Int64? ConvertToInt64(this string value)
{
return value.Convert<Int64>(Int64.TryParse);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment