Last active
January 14, 2018 06:05
-
-
Save dahlbyk/879adfe5cd6b19604fae71229208833a to your computer and use it in GitHub Desktop.
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
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