Last active
October 11, 2015 19:48
-
-
Save Larry57/3910180 to your computer and use it in GitHub Desktop.
Universal 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 class DuckTryParse | |
{ | |
public static bool TryParse<duck>(string stringToParse, out duck value) | |
{ | |
var method = MethodCache<duck>.TryParse; | |
if (method == null || !method(stringToParse, out value)) | |
{ | |
value = default(duck); | |
return false; | |
} | |
return true; | |
} | |
delegate bool TryParseSignature<duck>(string value, out duck result); | |
class MethodCache<duck> | |
{ | |
public static readonly TryParseSignature<duck> TryParse; | |
static MethodCache() | |
{ | |
var method = typeof(duck).GetMethod("TryParse", BindingFlags.Static | BindingFlags.Public, null, new Type[] { typeof(string), typeof(duck).MakeByRefType() }, null); | |
if (method != null) | |
TryParse = (TryParseSignature<duck>)Delegate.CreateDelegate(typeof(TryParseSignature<duck>), method); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment